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

OHRI-1963 Enable editing of L&D form infant details in OHRI #1689

Merged
merged 4 commits into from
Nov 28, 2023
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
14 changes: 12 additions & 2 deletions packages/esm-ohri-pmtct-app/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,17 @@ export function getEstimatedDeliveryDate(patientUuid: string, pTrackerId: string
});
}

export function getIdentifierInfo(identifier: string) {
return openmrsFetch(
`${BASE_WS_API_URL}patient?identifier=${identifier}&v=custom:(identifiers:(identifier,identifierType:(uuid,display)),person:(uuid,display))`,
).then(({ data }) => {
if (data) {
return data;
}
return null;
});
}

export function fetchMotherHIVStatus(patientUuid: string, pTrackerId: string) {
return openmrsFetch(
`${BASE_WS_API_URL}reportingrest/dataSet/${motherHivStatusReport}?person_uuid=${patientUuid}&ptracker_id=${pTrackerId}`,
Expand All @@ -93,7 +104,7 @@ export function fetchMotherHIVStatus(patientUuid: string, pTrackerId: string) {
});
}

export function fetchChildLatestFinalOutcome(childUuid: string, conceptUuid: string, encounterTypeUuid){
export function fetchChildLatestFinalOutcome(childUuid: string, conceptUuid: string, encounterTypeUuid) {
let params = `patient=${childUuid}&code=${conceptUuid}${
encounterTypeUuid ? `&encounter.type=${encounterTypeUuid}` : ''
}`;
Expand All @@ -102,7 +113,6 @@ export function fetchChildLatestFinalOutcome(childUuid: string, conceptUuid: str
return openmrsFetch(`/ws/fhir2/R4/Observation?${params}`).then(({ data }) => {
return data.entry?.length ? data.entry[0].resource.valueCodeableConcept.coding[0]?.display : null;
});

}

// Get family relationships from patient uuid
Expand Down
2 changes: 1 addition & 1 deletion packages/esm-ohri-pmtct-app/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import {
OHRIWelcomeSection,
createConditionalDashboardGroup,
} from '@ohri/openmrs-esm-ohri-commons-lib';
import { generateInfantPTrackerId } from './utils/ptracker-forms-helpers';
import { generateInfantPTrackerId } from './utils/pmtct-helpers';

export const importTranslation = require.context('../translations', false, /.json$/, 'lazy');

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { Patient, PatientIdentifier } from '../api/types';
import { findObsByConcept, findChildObsInTree, getObsValueCoded } from '../utils/obs-encounter-utils';
import { updatePatientPtracker } from './current-ptracker-action';
import { getConfig } from '@openmrs/esm-framework';
import { getIdentifierAssignee } from '../utils/pmtct-helpers';
import { fetchPatientRelationships } from '@ohri/openmrs-esm-ohri-commons-lib';

// necessary data points about an infact captured at birth
const infantDetailsGroup = '1c70c490-cafa-4c95-9fdd-a30b62bb78b8';
Expand All @@ -20,16 +22,16 @@ export const MotherToChildLinkageSubmissionAction: PostSubmissionAction = {
applyAction: async function ({ patient, encounters, sessionMode }) {
const encounter = encounters[0];
const encounterLocation = encounter.location['uuid'];
// only do this the first time the form is entered
if (sessionMode !== 'enter') {
// only do this in enter or edit mode
if (sessionMode === 'view') {
return;
}

const preferredIdentifierSource = await getPreferredIdentifierSource();
await updatePatientPtracker(encounter, encounterLocation, patient.id);
const infantsToCreate = await Promise.all(
findObsByConcept(encounter, infantDetailsGroup).map(async (obsGroup) =>
constructPatientObjectFromObsData(obsGroup, encounterLocation, preferredIdentifierSource),
constructPatientObjectFromObsData(obsGroup, encounterLocation, preferredIdentifierSource, sessionMode, patient),
),
);
const newInfantsToCreate = await Promise.all(infantsToCreate.filter((infant) => infant !== null));
Expand All @@ -53,33 +55,55 @@ async function constructPatientObjectFromObsData(
obsGroup,
encounterLocation: string,
preferredIdentifierSource: string,
sessionMode: string,
parent: fhir.Patient,
): Promise<Patient> {
// check if infant is alive
const lifeStatusAtBirth = findChildObsInTree(obsGroup, infantLifeStatus);
// the infant is alive hence eligible for registration
if (getObsValueCoded(lifeStatusAtBirth) == aliveStatus) {
// the infant is alive hence eligible for registration
const patient: Patient = {
identifiers: [],
person: {
names: [
{
givenName: 'TBD',
middleName: 'TBD',
familyName: 'TBD',
preferred: true,
},
],
gender: inferGenderFromObs(findChildObsInTree(obsGroup, infantGender)),
birthdate: findChildObsInTree(obsGroup, infantDOB)?.value,
birthdateEstimated: false,
dead: false,
deathDate: null,
causeOfDeath: '',
},
};
// PTracker ID
const pTrackerId = findChildObsInTree(obsGroup, infantPTrackerId)?.value;
if (pTrackerId) {
const existingpTrackerAssignee = await getIdentifierAssignee(pTrackerId, PtrackerIdentifierType);
if (existingpTrackerAssignee) {
if (sessionMode === 'enter') {
throw new Error(
`PTracker Id (${pTrackerId}) already assigned to patient (${existingpTrackerAssignee.display})`,
);
} else {
//In edit mode, only throw error if the patient with the existing PTracker is not linked with the current mother
const parentRelationships = await fetchPatientRelationships(parent.id);
const isAlreadyLinked = parentRelationships.some(
Copy link
Contributor

Choose a reason for hiding this comment

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

🙌🏿

(relationship) => relationship.personB.uuid === existingpTrackerAssignee.uuid,
);
if (!isAlreadyLinked) {
throw new Error(
`PTracker Id (${pTrackerId}) already assigned to patient (${existingpTrackerAssignee.display})`,
);
}
return null;
}
}
const patient: Patient = {
identifiers: [],
person: {
names: [
{
givenName: 'TBD',
middleName: 'TBD',
familyName: 'TBD',
preferred: true,
},
],
gender: inferGenderFromObs(findChildObsInTree(obsGroup, infantGender)),
birthdate: findChildObsInTree(obsGroup, infantDOB)?.value,
birthdateEstimated: false,
dead: false,
deathDate: null,
causeOfDeath: '',
},
};

patient.identifiers = [
{
identifier: pTrackerId,
Expand All @@ -88,16 +112,18 @@ async function constructPatientObjectFromObsData(
preferred: false,
},
];
// generate the preferred identifier
const preferredIdentifier: PatientIdentifier = {
identifier: await (await generateIdentifier(preferredIdentifierSource)).data.identifier,
identifierType: OpenmrsClassicIdentifierType,
location: encounterLocation,
preferred: true,
};
patient.identifiers.push(preferredIdentifier);
return patient;
}
// generate the preferred identifier
const preferredIdentifier: PatientIdentifier = {
identifier: await (await generateIdentifier(preferredIdentifierSource)).data.identifier,
identifierType: OpenmrsClassicIdentifierType,
location: encounterLocation,
preferred: true,
};
patient.identifiers.push(preferredIdentifier);
return patient;
} else {
throw new Error('Please provide child PTracker Id');
}
return null;
}
Expand Down
26 changes: 26 additions & 0 deletions packages/esm-ohri-pmtct-app/src/utils/pmtct-helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { getIdentifierInfo } from '../api/api';

export const generateInfantPTrackerId = (fieldId: string, motherPtrackerId: string): string | undefined => {
if (!fieldId || !motherPtrackerId) return;
return fieldId === 'infantPtrackerid'
? motherPtrackerId + '1'
: fieldId.includes('_')
? motherPtrackerId.concat((Number(fieldId.split('_')[1]) + 1).toString())
: undefined;
};

export const getIdentifierAssignee = (identifier: string, identifierType: string) => {
return getIdentifierInfo(identifier).then((data) => {
if (data) {
for (const result of data.results) {
Copy link
Member

Choose a reason for hiding this comment

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

What happens if data has no results attribute?

Copy link
Member

Choose a reason for hiding this comment

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

This comment also applies to the lines below, you better explicitly check or add the question marks

Copy link
Contributor Author

Choose a reason for hiding this comment

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

In this case, by the time we get here, all the other possible errors were checked and the call is fine. If there's no data, it only means that there's no patient with that identifier meaning it's ok to go ahead and assign it to the current patient.

for (const identifierObj of result.identifiers) {
if (identifierObj.identifier === identifier && identifierObj.identifierType.uuid === identifierType) {
return result.person;
}
}
}
return {};
}
return {};
});
};
11 changes: 0 additions & 11 deletions packages/esm-ohri-pmtct-app/src/utils/ptracker-forms-helpers.ts

This file was deleted.