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

Adding file attachment support #128

Merged
merged 17 commits into from
Nov 2, 2023
Merged
Show file tree
Hide file tree
Changes from 12 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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
"react-scroll": "^1.8.2",
"react-test-renderer": "^16.9.0",
"react-waypoint": "^10.3.0",
"react-webcam": "^7.1.1",
"semver": "^7.3.5",
"yup": "^0.29.1"
},
Expand Down
63 changes: 62 additions & 1 deletion src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { isUuid } from '../utils/boolean-utils';

export function saveEncounter(abortController: AbortController, payload, encounterUuid?: string) {
const url = !!encounterUuid ? `/ws/rest/v1/encounter/${encounterUuid}?v=full` : `/ws/rest/v1/encounter?v=full`;

return openmrsFetch(url, {
headers: {
'Content-Type': 'application/json',
Expand All @@ -17,6 +18,48 @@ export function saveEncounter(abortController: AbortController, payload, encount
});
}

export function saveAttachment(patientUuid, content, conceptUuid, date, encounterUUID, abortController) {
const url = '/ws/rest/v1/attachment';

const formData = new FormData();

const cameraUploadType = content
?.split(';')[0]
.split(':')[1]
.split('/')[1];

const fileCaption = typeof content === 'object' ? content.name : `camera-upload.${cameraUploadType}`;

formData.append('fileCaption', fileCaption);
formData.append('patient', patientUuid);

if (typeof content === 'object') {
formData.append('file', content);
} else {
formData.append('file', new File([''], 'OHRIFileConceptTest.png'), 'OHRIFileConceptTest.png');
arodidev marked this conversation as resolved.
Show resolved Hide resolved
formData.append('base64Content', content);
}
formData.append(
'json',
JSON.stringify({
person: patientUuid,
concept: conceptUuid,
groupMembers: [],
obsDatetime: date,
encounter: encounterUUID,
}),
);

return openmrsFetch(url, {
method: 'POST',
// headers: {
// 'Content-Type': 'multipart/form-data',
kajambiya marked this conversation as resolved.
Show resolved Hide resolved
// },
signal: abortController.signal,
body: formData,
});
}

export function getConcept(conceptUuid: string, v: string): Observable<any> {
return openmrsObservableFetch(`/ws/rest/v1/concept/${conceptUuid}?v=${v}`).pipe(map(response => response['data']));
}
Expand All @@ -32,7 +75,7 @@ export async function getPreviousEncounter(patientUuid: string, encounterType: s
let response = await openmrsFetch(`/ws/fhir2/R4/Encounter?${query}`);
if (response.data.entry.length) {
const latestEncounter = response.data.entry[0].resource.id;
response = await openmrsFetch(`/ws/rest/v1/encounter/${latestEncounter}?v=${encounterRepresentation}`)
response = await openmrsFetch(`/ws/rest/v1/encounter/${latestEncounter}?v=${encounterRepresentation}`);
return response.data;
}
return null;
Expand Down Expand Up @@ -101,3 +144,21 @@ export async function fetchClobData(form: OpenmrsForm): Promise<any | null> {

return clobDataResponse;
}

function dataURItoFile(dataURI: string) {
const byteString = atob(dataURI.split(',')[1]);
const mimeString = dataURI
.split(',')[0]
.split(':')[1]
.split(';')[0];

// write the bytes of the string to a typed array
const buffer = new Uint8Array(byteString.length);

for (let i = 0; i < byteString.length; i++) {
buffer[i] = byteString.charCodeAt(i);
}

const blob = new Blob([buffer], { type: mimeString });
return blob;
}
5 changes: 4 additions & 1 deletion src/api/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,8 @@ export interface OHRIFormQuestionOptions {
};
isDateTime?: { labelTrue: boolean; labelFalse: boolean };
usePreviousValueDisabled?: boolean;
allowedFileTypes?: Array<string>;
allowMultiple?: boolean; //Allow Single File Attachments and Multiple file attachments
arodidev marked this conversation as resolved.
Show resolved Hide resolved
datasource?: { name: string; config?: Record<string, any> };
isSearchable?: boolean;
}
Expand All @@ -185,7 +187,8 @@ export type RenderType =
| 'encounter-location'
| 'textarea'
| 'toggle'
| 'fixed-value';
| 'fixed-value'
| 'file'; //allow the form engine to recognize and handle the new file component
arodidev marked this conversation as resolved.
Show resolved Hide resolved

export interface PostSubmissionAction {
applyAction(
Expand Down
22 changes: 19 additions & 3 deletions src/components/encounter/ohri-encounter-form.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { isEmpty, isEmpty as isValueEmpty, OHRIFieldValidator } from '../../vali
import { InstantEffect } from '../../utils/instant-effect';
import { FormSubmissionHandler } from '../../ohri-form.component';
import { evaluateAsyncExpression, evaluateExpression } from '../../utils/expression-runner';
import { getPreviousEncounter, saveEncounter } from '../../api/api';
import { getPreviousEncounter, saveAttachment, saveEncounter } from '../../api/api';
import { isTrue } from '../../utils/boolean-utils';
import { scrollIntoView } from '../../utils/ohri-sidebar';
import { useEncounter } from '../../hooks/useEncounter';
Expand Down Expand Up @@ -403,9 +403,10 @@ export const OHRIEncounterForm: React.FC<OHRIEncounterFormProps> = ({
const handleFormSubmit = (values: Record<string, any>) => {
const obsForSubmission = [];
fields
.filter(field => field.value || field.type == 'obsGroup' ) // filter out fields with empty values except groups
.filter(field => field.value || field.type == 'obsGroup') // filter out fields with empty values except groups
.filter(field => !field.isParentHidden && !field.isHidden && (field.type == 'obs' || field.type == 'obsGroup'))
.filter(field => !field['groupId']) // filter out grouped obs
.filter(field => field.questionOptions.rendering !== 'file')
arodidev marked this conversation as resolved.
Show resolved Hide resolved
.filter(field => !field.questionOptions.isTransient) //filter out fields marked as transient
.forEach(field => {
if (field.type == 'obsGroup') {
Expand Down Expand Up @@ -484,7 +485,22 @@ export const OHRIEncounterForm: React.FC<OHRIEncounterFormProps> = ({

if (encounterForSubmission.obs?.length || encounterForSubmission.orders?.length) {
const ac = new AbortController();
return saveEncounter(ac, encounterForSubmission, encounter?.uuid);
return saveEncounter(ac, encounterForSubmission, encounter?.uuid)
.then(response => response.json())
.then(encounter => {
fields
?.filter(field => field?.questionOptions.rendering === 'file')
.forEach(field => {
saveAttachment(
encounter.patient.uuid,
field?.value?.value,
field?.questionOptions.concept,
new Date().toISOString(),
encounter.uuid,
ac,
);
});
});
arodidev marked this conversation as resolved.
Show resolved Hide resolved
}
};

Expand Down
3 changes: 3 additions & 0 deletions src/components/inputs/camera/camera.component.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
.CaptureButton{
margin: 0.5rem 0;
}
arodidev marked this conversation as resolved.
Show resolved Hide resolved
33 changes: 33 additions & 0 deletions src/components/inputs/camera/camera.component.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import React from 'react';
import Webcam from 'react-webcam';
import { Button } from '@carbon/react';
import { Camera as CameraIcon } from '@carbon/react/icons';
import styles from './camera.component.scss';

interface CameraProps {
handleImages: (state: any) => void;
}

const Camera: React.FC<CameraProps> = ({ handleImages }) => {
const webcamRef = React.useRef(null);

const capture = React.useCallback(() => {
const imageSrc = webcamRef.current.getScreenshot();
handleImages(imageSrc);
}, [webcamRef]);

const videoConstraints = {
facingMode: 'user',
};

return (
<div>
<Webcam audio={false} ref={webcamRef} screenshotFormat="image/png" videoConstraints={videoConstraints} />
<div className={styles.CaptureButton}>
<Button onClick={capture} type="button" hasIconOnly renderIcon={() => <CameraIcon size={24} />}></Button>
</div>
</div>
);
};

export default Camera;
63 changes: 63 additions & 0 deletions src/components/inputs/file/file.component.scss
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
.label{
font-family: IBM Plex Sans;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 30px; /* 128.571% */
letter-spacing: 0.16px;
color: #525252,
}
.saveFile{
margin: 0;
}

.capturedImage{
width: 100%;
}

.Caption{
display: flex;
}
.closeIcon{
margin: 0 1rem;
}

.uploadSelector{
display: flex;
align-items: center;
margin-bottom: 1rem;
}
.selectorButton{
margin-right: 1rem;
}

.Caption{
margin-top: 5px;
}

.imageDescription {
margin-top: 5px;
}

.fileUploader{
background-color: rgb(255, 255, 255);
padding: 1rem;
}

.cameraUploader{
margin: 1rem 0;
background-color: white;
padding: 1rem;
}
.camButton{
margin-bottom: 1rem;
}

.cameraPreview{
margin-top: 1rem;
}

.imageContent{
padding: 0;
margin: 0;
}
Loading
Loading