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) O3-3276: Add support for printing patient identification stickers #1847

Merged
merged 3 commits into from
Jun 17, 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
@@ -0,0 +1,189 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation, type TFunction } from 'react-i18next';
import { useReactToPrint } from 'react-to-print';
import { Button, InlineLoading, ModalBody, ModalFooter, ModalHeader } from '@carbon/react';
import { age, displayName, showSnackbar, useConfig } from '@openmrs/esm-framework';
import { type ConfigObject } from '../config-schema';
import styles from './print-identifier-sticker-modal.scss';

interface PrintIdentifierStickerProps {
closeModal: () => void;
patient: fhir.Patient;
}

interface PrintComponentProps extends Partial<ConfigObject> {
patientDetails: {
address?: fhir.Address[];
age?: string;
dateOfBirth?: string;
gender?: string;
id?: string;
identifiers?: fhir.Identifier[];
name?: string;
photo?: fhir.Attachment[];
};
printRef: React.RefObject<HTMLDivElement>;
t: TFunction;
}

const PrintIdentifierSticker: React.FC<PrintIdentifierStickerProps> = ({ closeModal, patient }) => {
const { t } = useTranslation();
const { printIdentifierStickerFields, printIdentifierStickerSize, excludePatientIdentifierCodeTypes } =
useConfig<ConfigObject>();
const contentToPrintRef = useRef(null);
const onBeforeGetContentResolve = useRef<() => void | null>(null);
const [isPrinting, setIsPrinting] = useState(false);
const headerTitle = t('patientIdentifierSticker', 'Patient identifier sticker');

useEffect(() => {
if (isPrinting && onBeforeGetContentResolve.current) {
onBeforeGetContentResolve.current();
}
}, [isPrinting, printIdentifierStickerSize]);

const patientDetails = useMemo(() => {
if (!patient) {
return {};
}

const getGender = (gender: string): string => {
switch (gender) {
case 'male':
return t('male', 'Male');
case 'female':
return t('female', 'Female');
case 'other':
return t('other', 'Other');
case 'unknown':
return t('unknown', 'Unknown');
default:
return gender;
}
};

const identifiers =
patient.identifier?.filter(
(identifier) => !excludePatientIdentifierCodeTypes?.uuids.includes(identifier.type.coding[0].code),
) ?? [];

return {
address: patient.address,
age: age(patient.birthDate),
dateOfBirth: patient.birthDate,
gender: getGender(patient.gender),
id: patient.id,
identifiers: [...identifiers],
name: patient ? displayName(patient) : '',
photo: patient.photo,
};
}, [excludePatientIdentifierCodeTypes?.uuids, patient, t]);

const handleBeforeGetContent = useCallback(
() =>
new Promise<void>((resolve) => {
if (patient && headerTitle) {
onBeforeGetContentResolve.current = resolve;
setIsPrinting(true);
}
}),
[headerTitle, patient],
);

const handleAfterPrint = useCallback(() => {
onBeforeGetContentResolve.current = null;
setIsPrinting(false);
closeModal();
}, [closeModal]);

const handlePrintError = useCallback(
(errorLocation, error) => {
onBeforeGetContentResolve.current = null;

showSnackbar({
isLowContrast: false,
kind: 'error',
title: t('printError', 'Print error'),
subtitle: t('printErrorExplainer', 'An error occurred in "{{errorLocation}}": ', { errorLocation }) + error,
});

setIsPrinting(false);
},
[t],
);

const handlePrint = useReactToPrint({
content: () => contentToPrintRef.current,
documentTitle: `${patientDetails.name} - ${headerTitle}`,
onAfterPrint: handleAfterPrint,
onBeforeGetContent: handleBeforeGetContent,
onPrintError: handlePrintError,
});

return (
<>
<ModalHeader closeModal={closeModal} title={t('printIdentifierSticker', 'Print identifier sticker')} />
<ModalBody>
<PrintComponent
patientDetails={patientDetails}
printIdentifierStickerFields={printIdentifierStickerFields}
printIdentifierStickerSize={printIdentifierStickerSize}
printRef={contentToPrintRef}
t={t}
/>
</ModalBody>
<ModalFooter>
<Button kind="secondary" onClick={closeModal}>
{t('cancel', 'Cancel')}
</Button>
<Button className={styles.button} disabled={isPrinting} onClick={handlePrint} kind="primary">
{isPrinting ? (
<InlineLoading className={styles.loader} description={t('printing', 'Printing') + '...'} />
) : (
t('print', 'Print')
)}
</Button>
</ModalFooter>
</>
);
};

const PrintComponent = ({
patientDetails,
printIdentifierStickerFields,
printIdentifierStickerSize,
printRef,
t,
}: PrintComponentProps) => {
return (
<div className={styles.stickerContainer} ref={printRef}>
<style type="text/css" media="print">
{`
@page {
size: ${printIdentifierStickerSize};
}
`}
</style>
Comment on lines +159 to +165
Copy link
Member

@denniskigen denniskigen Jun 17, 2024

Choose a reason for hiding this comment

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

@ibacher it's trivial to add a config property that governs which orientation to default to and then it would leverage this approach. Should I add one and make it default to portrait? (@jnsereko is there a specific requirement for a default orientation for this feature?)

Copy link
Member

Choose a reason for hiding this comment

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

Scratch that, it appears that it's not so straightforward to change the orientation for custom sizes (like the default 4in 6in value). For standard page sizes, something like this works well:

const  { printPageOrientation } = useConfig();

<style type="text/css" media="print">
  {`
    @page {
      size: A3 ${printPageOrientation};
    }
  `}
</style>

Copy link
Member

Choose a reason for hiding this comment

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

It looks like this is something else worth looking into when evaluating whether to move away from this library. I'm proceeding to merge to unblock Madiro for now.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I am going to create a follow up ticket to investigate what's breaking the Library and how to move on. Thank you so much @denniskigen

{printIdentifierStickerFields.includes('name') && <div className={styles.patientName}>{patientDetails.name}</div>}
<div className={styles.detailsGrid}>
{patientDetails.identifiers.map((identifier) => {
return (
<p key={identifier?.id}>
{identifier?.type?.text}: <strong>{identifier?.value}</strong>
</p>
);
})}
<p>
{t('sex', 'Sex')}: <strong>{patientDetails.gender}</strong>
</p>
<p>
{t('dob', 'DOB')}: <strong>{patientDetails.dateOfBirth}</strong>
</p>
<p>
{t('age', 'Age')}: <strong>{patientDetails.age}</strong>
</p>
</div>
</div>
);
};

export default PrintIdentifierSticker;
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
@use '@carbon/layout';
@use '@carbon/type';

.stickerContainer {
padding: 0.5rem 1rem;
}

.row {
margin: layout.$spacing-03 0rem 0rem;
display: flex;
flex-flow: row wrap;
gap: layout.$spacing-05;
}

.gridRow {
padding: 0px;
display: flex;
flex-direction: row;
justify-content: space-between;

div {
margin-left: 0px;
margin-bottom: 5px;
}
}

.patientName {
font-size: 1.5rem;
font-weight: bolder;
margin-bottom: 5px;
}

.button {
:global(.cds--inline-loading) {
min-height: 1rem !important;
}
}

.detailsGrid {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.5rem 0;
margin-top: 0.5rem;
}

.loader {
:global(.cds--inline-loading__text) {
@include type.type-style('body-01');
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import React from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
import { useReactToPrint } from 'react-to-print';
import { mockPatient } from 'tools';
import PrintIdentifierSticker from './print-identifier-sticker-modal.component';

const mockedCloseModal = jest.fn();
const mockedUseReactToPrint = jest.mocked(useReactToPrint);

jest.mock('react-to-print', () => {
const originalModule = jest.requireActual('react-to-print');

return {
...originalModule,
useReactToPrint: jest.fn(),
};
});

jest.mock('@openmrs/esm-framework', () => {
const originalModule = jest.requireActual('@openmrs/esm-framework');

return {
...originalModule,
useConfig: jest.fn().mockImplementation(() => ({
printIdentifierStickerFields: ['name', 'identifier', 'age', 'dateOfBirth', 'gender'],
})),
};
});

describe('PrintIdentifierSticker', () => {
test('renders the component', () => {
renderPrintIdentifierSticker();

expect(screen.getByText(/Print Identifier Sticker/i)).toBeInTheDocument();
expect(screen.getByText('John Wilson')).toBeInTheDocument();
expect(screen.getByText('100GEJ')).toBeInTheDocument();
expect(screen.getByText('1972-04-04')).toBeInTheDocument();
});

test('calls closeModal when cancel button is clicked', async () => {
const user = userEvent.setup();

renderPrintIdentifierSticker();

const cancelButton = screen.getByRole('button', { name: /Cancel/i });
expect(cancelButton).toBeInTheDocument();

await user.click(cancelButton);
expect(mockedCloseModal).toHaveBeenCalled();
});

test('calls the print function when print button is clicked', async () => {
const handlePrint = jest.fn();
mockedUseReactToPrint.mockReturnValue(handlePrint);

const user = userEvent.setup();

renderPrintIdentifierSticker();

const printButton = screen.getByRole('button', { name: /Print/i });
expect(printButton).toBeInTheDocument();

await user.click(printButton);
expect(handlePrint).toHaveBeenCalled();
});
});
function renderPrintIdentifierSticker() {
render(<PrintIdentifierSticker patient={mockPatient} closeModal={mockedCloseModal} />);
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ interface PatientBannerProps {
const PatientBanner: React.FC<PatientBannerProps> = ({ patient, patientUuid, hideActionsOverflow }) => {
const patientBannerRef = useRef(null);
const [isTabletViewport, setIsTabletViewport] = useState(false);
const [showContactDetails, setShowContactDetails] = useState(false);

useEffect(() => {
const currentRef = patientBannerRef.current;
Expand All @@ -37,7 +38,6 @@ const PatientBanner: React.FC<PatientBannerProps> = ({ patient, patientUuid, hid

const patientName = patient ? displayName(patient) : '';

const [showContactDetails, setShowContactDetails] = useState(false);
const toggleContactDetails = useCallback(() => {
setShowContactDetails((value) => !value);
}, []);
Expand All @@ -60,27 +60,29 @@ const PatientBanner: React.FC<PatientBannerProps> = ({ patient, patientUuid, hid
</div>
<PatientBannerPatientInfo patient={patient} />
<div className={styles.buttonCol}>
{!hideActionsOverflow ? (
<PatientBannerActionsMenu
actionsSlotName="patient-actions-slot"
isDeceased={patient.deceasedBoolean}
patientUuid={patientUuid}
/>
) : null}
<div className={styles.buttonRow}>
denniskigen marked this conversation as resolved.
Show resolved Hide resolved
{!hideActionsOverflow ? (
<PatientBannerActionsMenu
actionsSlotName="patient-actions-slot"
isDeceased={patient.deceasedBoolean}
patientUuid={patientUuid}
/>
) : null}
</div>
{!showDetailsButtonBelowHeader ? (
<PatientBannerToggleContactDetailsButton
className={styles.toggleContactDetailsButton}
toggleContactDetails={toggleContactDetails}
showContactDetails={showContactDetails}
toggleContactDetails={toggleContactDetails}
/>
) : null}
</div>
</div>
{showDetailsButtonBelowHeader ? (
<PatientBannerToggleContactDetailsButton
className={styles.toggleContactDetailsButton}
toggleContactDetails={toggleContactDetails}
showContactDetails={showContactDetails}
toggleContactDetails={toggleContactDetails}
/>
) : null}
{showContactDetails && (
Expand All @@ -90,7 +92,7 @@ const PatientBanner: React.FC<PatientBannerProps> = ({ patient, patientUuid, hid
[styles.tabletContactDetails]: isTabletViewport,
})}
>
<PatientBannerContactDetails patientId={patient?.id} deceased={isDeceased} />
<PatientBannerContactDetails deceased={isDeceased} patientId={patient?.id} />
</div>
)}
</header>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
background-color: $ui-01;
}

.activePatientContainer,
.activePatientContainer,
.deceasedPatientContainer {
background-color: $ui-01;
}
Expand Down
Loading
Loading