Skip to content

Commit

Permalink
feat(pn-9010): Refactoring Mixpanel utility functions (#1164)
Browse files Browse the repository at this point in the history
  • Loading branch information
alessandrogelmi authored Mar 29, 2024
1 parent 4481211 commit 8bbb018
Show file tree
Hide file tree
Showing 183 changed files with 3,707 additions and 1,992 deletions.
9 changes: 2 additions & 7 deletions packages/pn-commons/src/components/Header/Header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,6 @@ type HeaderProps = {
userActions?: Array<UserAction>;
/** Actions linked to user dropdown */
onAssistanceClick?: () => void;
/** Track product switch action */
eventTrackingCallbackProductSwitch?: (target: string) => void;
/** Whether there is a logged user */
isLogged?: boolean;
/** Enable assistance button */
Expand All @@ -53,7 +51,6 @@ const Header: React.FC<HeaderProps> = ({
enableDropdown,
userActions,
onAssistanceClick,
eventTrackingCallbackProductSwitch,
isLogged,
enableAssistanceButton,
}) => {
Expand All @@ -64,13 +61,11 @@ const Header: React.FC<HeaderProps> = ({
};

const handleProductSelection = (product: ProductEntity) => {
if (eventTrackingCallbackProductSwitch) {
eventTrackingCallbackProductSwitch(product.productUrl);
}
if (product.productUrl) {
/* eslint-disable-next-line functional/immutable-data */
window.location.assign(product.productUrl);
/** Here is necessary to clear sessionStorage otherwise when navigating through Area Riservata
/**
* Here is necessary to clear sessionStorage otherwise when navigating through Area Riservata
* we enter in a state where the user was previously logged in but Area Riservata and PN require
* another token-exchange. Since the user "seems" to be logged in due to the presence of the old token
* in session storage, the token-exchange doesn't happen and the application enters in a blank state.
Expand Down
4 changes: 0 additions & 4 deletions packages/pn-commons/src/components/Layout/Layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,6 @@ type Props = {
onLanguageChanged?: (langCode: string) => void;
/** event callback on app crash */
eventTrackingCallbackAppCrash?: (_error: Error, _errorInfo: ErrorInfo) => void;
/** Track product switch action */
eventTrackingCallbackProductSwitch?: (target: string) => void;
/** event on assistance click button */
eventTrackingCallbackRefreshPage?: () => void;
/** event on refresh page click button */
Expand Down Expand Up @@ -72,7 +70,6 @@ const Layout: React.FC<Props> = ({
userActions,
onLanguageChanged = () => {},
eventTrackingCallbackAppCrash,
eventTrackingCallbackProductSwitch,
eventTrackingCallbackRefreshPage,
onAssistanceClick,
isLogged,
Expand Down Expand Up @@ -106,7 +103,6 @@ const Layout: React.FC<Props> = ({
enableDropdown={enableUserDropdown}
userActions={userActions}
onAssistanceClick={onAssistanceClick}
eventTrackingCallbackProductSwitch={eventTrackingCallbackProductSwitch}
isLogged={isLogged}
enableAssistanceButton={enableAssistanceButton}
/>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@ type Props = {
historyButtonLabel: string;
showMoreButtonLabel: string;
showLessButtonLabel: string;
eventTrackingCallbackShowMore?: () => void;
disableDownloads?: boolean;
isParty?: boolean;
language?: string;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,6 @@ const TimelineStepCmp: React.FC<StepProps> = ({
* @param historyButtonClickHandler function called when user clicks on the history button
* @param showMoreButtonLabel label of show more button
* @param showLessButtonLabel label of show less button
* @param eventTrackingCallbackShowMore event tracking callback
* @param completeStatusHistory the whole history, sometimes some information from a different status must be retrieved
* @param disableDownloads if notification is disabled
* @param isParty if is party chip rendered with opacity for status cancellation in progress
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ import { Alert, Box, Button, CircularProgress, Link, RadioGroup, Typography } fr
import { downloadDocument } from '../../hooks';
import {
EventPaymentRecipientType,
EventPaymentStatusType,
F24PaymentDetails,
NotificationDetailPayment,
PaginationData,
PagoPAPaymentFullDetails,
PaymentAttachment,
PaymentAttachmentSName,
PaymentDetails,
PaymentInfoDetail,
PaymentStatus,
PaymentsData,
} from '../../models';
Expand All @@ -28,32 +26,6 @@ import NotificationPaymentTitle from './NotificationPaymentTitle';

const FAQ_NOTIFICATION_CANCELLED_REFUND = '/faq#notifica-pagata-rimborso';

const getPaymentsStatus = (
paginationData: PaginationData,
pagoPaF24: Array<PaymentDetails>
): EventPaymentStatusType => ({
page_number: paginationData.page,
count_payment: pagoPaF24.length,
count_canceled: pagoPaF24.filter(
(f) =>
f.pagoPa?.status === PaymentStatus.FAILED &&
f.pagoPa.detail === PaymentInfoDetail.PAYMENT_CANCELED
).length,
count_error: pagoPaF24.filter(
(f) =>
f.pagoPa?.status === PaymentStatus.FAILED &&
f.pagoPa.detail !== PaymentInfoDetail.PAYMENT_CANCELED &&
f.pagoPa.detail !== PaymentInfoDetail.PAYMENT_EXPIRED
).length,
count_expired: pagoPaF24.filter(
(f) =>
f.pagoPa?.status === PaymentStatus.FAILED &&
f.pagoPa.detail === PaymentInfoDetail.PAYMENT_EXPIRED
).length,
count_paid: pagoPaF24.filter((f) => f.pagoPa?.status === PaymentStatus.SUCCEEDED).length,
count_unpaid: pagoPaF24.filter((f) => f.pagoPa?.status === PaymentStatus.REQUIRED).length,
});

type Props = {
payments: PaymentsData;
isCancelled: boolean;
Expand Down Expand Up @@ -160,8 +132,10 @@ const NotificationPaymentRecipient: React.FC<Props> = ({
const paymentsLoaded = paginatedPayments.every((payment) => !payment.isLoading);
if (paymentsLoaded) {
// the tracked event wants only the status of the current paged payments
const pagePaymentsStatus = getPaymentsStatus(paginationData, paginatedPayments);
handleTrackEventFn(EventPaymentRecipientType.SEND_PAYMENT_STATUS, pagePaymentsStatus);
handleTrackEventFn(EventPaymentRecipientType.SEND_PAYMENT_STATUS, {
paginationData,
paginatedPayments,
});
}
}, [payments]);

Expand Down Expand Up @@ -287,11 +261,19 @@ const NotificationPaymentRecipient: React.FC<Props> = ({
</Button>
)}
{selectedPayment &&
pagoPaF24.find((payment) => payment.pagoPa?.noticeCode === selectedPayment.noticeCode)
?.f24 ? (
pagoPaF24.find(
(payment) => payment.pagoPa?.noticeCode === selectedPayment?.noticeCode
)?.f24 ? (
<Box key="attachment" data-testid="f24-download">
<NotificationPaymentF24Item
handleTrackDownloadF24={
f24Item={
pagoPaF24.find(
(payment) => payment.pagoPa?.noticeCode === selectedPayment?.noticeCode
)?.f24 as F24PaymentDetails
}
getPaymentAttachmentAction={getPaymentAttachmentAction}
isPagoPaAttachment
handleTrackDownloadF24={() =>
void handleTrackEventFn(EventPaymentRecipientType.SEND_F24_DOWNLOAD)
}
handleTrackDownloadF24Success={() =>
Expand All @@ -300,13 +282,6 @@ const NotificationPaymentRecipient: React.FC<Props> = ({
handleTrackDownloadF24Timeout={() =>
void handleTrackEventFn(EventPaymentRecipientType.SEND_F24_DOWNLOAD_TIMEOUT)
}
f24Item={
pagoPaF24.find(
(payment) => payment.pagoPa?.noticeCode === selectedPayment.noticeCode
)?.f24 as F24PaymentDetails
}
getPaymentAttachmentAction={getPaymentAttachmentAction}
isPagoPaAttachment
timerF24={timerF24}
disableDownload={areOtherDowloading}
handleDownload={setAreOtherDowloading}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ const NotificationPaymentTitle: React.FC<Props> = ({
}) => {
const FAQ_NOTIFICATION_COSTS = '/faq#costi-di-notifica';
const notificationCostsFaqLink = `${landingSiteUrl}${FAQ_NOTIFICATION_COSTS}`;

const FaqLink = (
<Link
href={notificationCostsFaqLink}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,26 +9,19 @@ const StatusTooltip = ({
tooltip,
label,
color,
eventTrackingCallback,
tooltipProps,
chipProps,
}: {
tooltip: string | ReactNode;
label: string;
color: 'warning' | 'error' | 'success' | 'info' | 'default' | 'primary' | 'secondary' | undefined;
eventTrackingCallback?: () => void;
tooltipProps?: Partial<TooltipProps>;
chipProps?: SxProps;
}) => {
const tooltipContent = <Fragment>{tooltip}</Fragment>;

return (
<CustomTooltip
openOnClick={false}
tooltipContent={tooltipContent}
onOpen={eventTrackingCallback}
tooltipProps={tooltipProps}
>
<CustomTooltip openOnClick={false} tooltipContent={tooltipContent} tooltipProps={tooltipProps}>
<Chip
id={`status-chip-${label}`}
label={label}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,32 +1,21 @@
import { vi } from 'vitest';

import { fireEvent, render, screen, waitFor } from '../../../test-utils';
import StatusTooltip from '../StatusTooltip';

const tooltip = 'mocked tooltip test';
const label = 'mocked label';
const classRoot = 'MuiChip-color';
const mockEventTrackingCallback = vi.fn();

async function testStatusTooltip(
color: 'warning' | 'error' | 'success' | 'info' | 'default' | 'primary' | 'secondary'
) {
const { getByRole } = render(
<StatusTooltip
tooltip={tooltip}
label={label}
color={color}
eventTrackingCallback={mockEventTrackingCallback}
/>
);
const { getByRole } = render(<StatusTooltip tooltip={tooltip} label={label} color={color} />);
const button = getByRole('button');
expect(button).toHaveTextContent(/mocked label/i);
const buttonClass = `${classRoot}${color.charAt(0).toUpperCase() + color.slice(1)}`;
expect(button.classList.contains(buttonClass)).toBe(true);
fireEvent.mouseOver(button);
await waitFor(() => {
expect(screen.getByRole('tooltip')).toHaveTextContent(/mocked tooltip test/i);
expect(mockEventTrackingCallback).toBeCalledTimes(1);
});
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,6 @@ type Props = {
pagesToShow?: Array<number>;
/** custom style */
sx?: SxProps;
/** event tracking function callback for page size */
eventTrackingCallbackPageSize?: (pageSize: number) => void;
/** hide size selector */
hideSizeSelector?: boolean;
};
Expand Down Expand Up @@ -76,7 +74,6 @@ export default function CustomPagination({
elementsPerPage = [10, 20, 50],
pagesToShow,
sx,
eventTrackingCallbackPageSize,
hideSizeSelector = false,
}: Props) {
const size = paginationData.size || elementsPerPage[0];
Expand All @@ -99,9 +96,6 @@ export default function CustomPagination({
// eslint-disable-next-line functional/immutable-data
paginationData.page = 0;
onPageRequest(paginationData);
if (eventTrackingCallbackPageSize) {
eventTrackingCallbackPageSize(selectedSize);
}
}
handleClose();
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@ let paginationData: PaginationData = {
};

const handlePageChange = vi.fn();
const mockEventTrackingPageSize = vi.fn();

describe('CustomPagination Component', () => {
afterEach(() => {
Expand All @@ -26,11 +25,7 @@ describe('CustomPagination Component', () => {
it('renders custom pagination', () => {
// render component
const { getByTestId } = render(
<CustomPagination
paginationData={paginationData}
eventTrackingCallbackPageSize={mockEventTrackingPageSize}
onPageRequest={handlePageChange}
/>
<CustomPagination paginationData={paginationData} onPageRequest={handlePageChange} />
);
const itemsPerPageSelector = getByTestId('itemsPerPageSelector');
expect(itemsPerPageSelector).toBeInTheDocument();
Expand All @@ -43,7 +38,6 @@ describe('CustomPagination Component', () => {
const { queryByTestId } = render(
<CustomPagination
paginationData={paginationData}
eventTrackingCallbackPageSize={mockEventTrackingPageSize}
onPageRequest={handlePageChange}
hideSizeSelector
/>
Expand All @@ -54,11 +48,7 @@ describe('CustomPagination Component', () => {

it('changes items per page', async () => {
const { container, getAllByRole, getByRole } = render(
<CustomPagination
paginationData={paginationData}
eventTrackingCallbackPageSize={mockEventTrackingPageSize}
onPageRequest={handlePageChange}
/>
<CustomPagination paginationData={paginationData} onPageRequest={handlePageChange} />
);
const button = getById(container, 'rows-per-page');
expect(button).toHaveTextContent(/50/i);
Expand All @@ -71,7 +61,6 @@ describe('CustomPagination Component', () => {
await waitFor(() => {
expect(button).toHaveTextContent(/20/i);
expect(handlePageChange).toBeCalledTimes(1);
expect(mockEventTrackingPageSize).toBeCalledTimes(1);
expect(handlePageChange).toBeCalledWith({
page: 0,
size: 20,
Expand Down
6 changes: 1 addition & 5 deletions packages/pn-commons/src/components/SideMenu/SideMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,9 @@ import SideMenuList from './SideMenuList';
type Props = {
menuItems: Array<SideMenuItem>;
selfCareItems?: Array<SideMenuItem>;
eventTrackingCallback?: (target: string) => void;
};

const SideMenu: FC<Props> = ({ menuItems, selfCareItems, eventTrackingCallback }) => {
const SideMenu: FC<Props> = ({ menuItems, selfCareItems }) => {
const [state, setState] = useState(false);
const navigate = useNavigate();
const location = useLocation();
Expand Down Expand Up @@ -86,9 +85,6 @@ const SideMenu: FC<Props> = ({ menuItems, selfCareItems, eventTrackingCallback }
};

const handleNavigation = (item: SideMenuItem, menuFlag?: boolean) => {
if (eventTrackingCallback) {
eventTrackingCallback(item.route);
}
if (isMobile && !menuFlag) {
setState(false);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -103,30 +103,23 @@ describe('SideMenu', () => {

it('menu navigation', async () => {
const mockedAction = vi.fn();
const eventTrackingCallback = vi.fn();
const menuItems = sideMenuItems.map((item) =>
item.action ? { ...item, action: mockedAction } : item
);
const { getByRole } = render(
<SideMenu menuItems={menuItems} eventTrackingCallback={eventTrackingCallback} />
);
const { getByRole } = render(<SideMenu menuItems={menuItems} />);
const ul = getByRole('navigation');
const buttons = within(ul).getAllByTestId(/^sideMenuItem-Item \d$/);
// no children
// navigation
const noChildrenIdx = menuItems.findIndex((item) => !item.children);
fireEvent.click(buttons[noChildrenIdx]);
expect(eventTrackingCallback).toBeCalledTimes(1);
expect(eventTrackingCallback).toBeCalledWith(menuItems[noChildrenIdx].route);
expect(mockNavigate).toBeCalledTimes(1);
expect(mockNavigate).toBeCalledWith(menuItems[noChildrenIdx].route);
expect(buttons[noChildrenIdx]).toHaveClass('Mui-selected');
// with children and notSelectable set to false
// navigate and open the accordion
const withChildrenIdx = menuItems.findIndex((item) => item.children && !item.notSelectable);
fireEvent.click(buttons[withChildrenIdx]);
expect(eventTrackingCallback).toBeCalledTimes(2);
expect(eventTrackingCallback).toBeCalledWith(menuItems[withChildrenIdx].route);
expect(mockNavigate).toBeCalledTimes(2);
expect(mockNavigate).toBeCalledWith(menuItems[withChildrenIdx].route);
const accordion0 = within(ul).getByTestId(`collapse-${menuItems[withChildrenIdx].label}`);
Expand All @@ -138,8 +131,6 @@ describe('SideMenu', () => {
(item) => item.children && item.notSelectable
);
fireEvent.click(buttons[withChildrenAndNotSelectableIdx]);
expect(eventTrackingCallback).toBeCalledTimes(3);
expect(eventTrackingCallback).toBeCalledWith(menuItems[withChildrenAndNotSelectableIdx].route);
expect(mockNavigate).toBeCalledTimes(2);
const accordion1 = within(ul).getByTestId(
`collapse-${menuItems[withChildrenAndNotSelectableIdx].label}`
Expand All @@ -153,8 +144,6 @@ describe('SideMenu', () => {
// no navigation and action call
const noChildrenAndNoRouteIdx = menuItems.findIndex((item) => !item.children && !item.route);
fireEvent.click(buttons[noChildrenAndNoRouteIdx]);
expect(eventTrackingCallback).toBeCalledTimes(4);
expect(eventTrackingCallback).toBeCalledWith(menuItems[noChildrenAndNoRouteIdx].route);
expect(mockNavigate).toBeCalledTimes(2);
expect(mockedAction).toBeCalledTimes(1);
expect(buttons[noChildrenAndNoRouteIdx]).toHaveClass('Mui-selected');
Expand Down
Loading

0 comments on commit 8bbb018

Please sign in to comment.