Skip to content

Commit

Permalink
feat/Date picker format should be according to current user locale (#137
Browse files Browse the repository at this point in the history
)

* fix failing tests

* remove unused imports
  • Loading branch information
kajambiya authored Nov 3, 2023
1 parent e790a4c commit 163481e
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 35 deletions.
12 changes: 6 additions & 6 deletions src/components/inputs/date/ohri-date.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@ import { OHRIFormContext } from '../../../ohri-form-context';
import { OHRIFieldValueView } from '../../value/view/ohri-field-value-view.component';
import { PreviousValueReview } from '../../previous-value-review/previous-value-review.component';
import styles from './ohri-date.scss';
import { formatDate } from '@openmrs/esm-framework';

const dateFormatter = new Intl.DateTimeFormat(window.navigator.language);
const locale = window.i18next.language == 'en' ? 'en-GB' : window.i18next.language;
const dateFormatter = new Intl.DateTimeFormat(locale);

const OHRIDate: React.FC<OHRIFormFieldProps> = ({ question, onChange, handler }) => {
const [field, meta] = useField(question.id);
Expand Down Expand Up @@ -104,7 +106,7 @@ const OHRIDate: React.FC<OHRIFormFieldProps> = ({ question, onChange, handler })
const rawDate = new Date(prevValue.value);

prevValue = {
display: dayjs(prevValue.value).format('M/D/YYYY HH:mm'),
display: formatDate(prevValue.value, { mode: 'wide' }),
value: [rawDate],
};
} else {
Expand Down Expand Up @@ -156,15 +158,13 @@ const OHRIDate: React.FC<OHRIFormFieldProps> = ({ question, onChange, handler })
id={question.id}
placeholder={placeholder}
labelText={question.label}
value={
field.value instanceof Date ? field.value.toLocaleDateString(window.navigator.language) : field.value
}
value={field.value instanceof Date ? field.value.toLocaleDateString(locale) : field.value}
// Added for testing purposes.
// Notes:
// Something strange is happening with the way events are propagated and handled by Carbon.
// When we manually trigger an onchange event using the 'fireEvent' lib, the handler below will
// be triggered as opposed to the former handler that only gets triggered at runtime.
onChange={e => onDateChange([dayjs(e.target.value, 'DD/MM/YYYY').toDate()])}
onChange={e => onDateChange([dayjs(e.target.value, placeholder.toUpperCase()).toDate()])}
disabled={question.disabled}
invalid={!isFieldRequiredError && errors.length > 0}
invalidText={errors[0]?.message}
Expand Down
19 changes: 9 additions & 10 deletions src/ohri-form.component.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,6 @@ import { mockPatient } from "../__mocks__/patient.mock";
import { mockSessionDataResponse } from "../__mocks__/session.mock";
import demoHtsOpenmrsForm from "../__mocks__/forms/omrs-forms/demo_hts-form.json";
import demoHtsOhriForm from "../__mocks__/forms/ohri-forms/demo_hts-form.json";
import { saveEncounter } from "./api/api";
import { openmrsFetch } from "@openmrs/esm-framework";
import { ObsSubmissionHandler } from './submission-handlers/base-handlers';
import { EncounterContext } from './ohri-form-context';

import {
assertFormHasAllFields,
Expand Down Expand Up @@ -56,6 +52,8 @@ when(mockOpenmrsFetch)
.calledWith(clobdataResourcePath)
.mockReturnValue({ data: demoHtsOhriForm });

const locale = window.i18next.language == 'en'? 'en-GB' : window.i18next.language;

//////////////////////////////////////////
////// Mocks
//////////////////////////////////////////
Expand Down Expand Up @@ -214,7 +212,7 @@ describe("OHRI Forms:", () => {
fireEvent.click(generalPopulationField);

// Assert that Transient Field has a value
expect(enrolmentDateField.value).toBe("9/9/2023")
expect(enrolmentDateField.value).toBe("09/09/2023")

// Simulate a successful form submission
await act(async () => {
Expand Down Expand Up @@ -343,18 +341,19 @@ describe("OHRI Forms:", () => {
// verify
await act(async () =>
expect(lmpField.value).toBe(
new Date("2022-07-06").toLocaleDateString("en-US")
new Date("2022-07-06").toLocaleDateString(locale)
)
);
await act(async () =>
expect(eddField.value).toBe(
new Date("2023-04-12").toLocaleDateString("en-US")
new Date("2023-04-12").toLocaleDateString(locale)
)
);
});

it("Should evaluate months on ART", async () => {
// setup
console.log(locale);
await act(async () => renderForm(null, months_on_art_form));
jest.useFakeTimers();
jest.setSystemTime(new Date(2022, 9, 1));
Expand All @@ -376,11 +375,11 @@ describe("OHRI Forms:", () => {
// verify
await act(async () =>
expect(artStartDateField.value).toBe(
new Date("2022-05-02T00:00:00.000+0000").toLocaleDateString("en-US")
new Date("2022-02-05T00:00:00.000+0000").toLocaleDateString(locale)
)
);
await act(async () => expect(assumeTodayToBe).toBe("7/11/2022"));
await act(async () => expect(monthsOnARTField.value).toBe("5"));
await act(async () => expect(monthsOnARTField.value).toBe("7"));
});

it("Should evaluate viral load status", async () => {
Expand Down Expand Up @@ -431,7 +430,7 @@ describe("OHRI Forms:", () => {
// verify
await act(async () =>
expect(enrollmentDate.value).toBe(
new Date("1975-07-06T00:00:00.000Z").toLocaleDateString("en-US")
new Date("1975-07-06T00:00:00.000Z").toLocaleDateString(locale)
)
);
await act(async () => expect(mrn.value).toBe(""));
Expand Down
39 changes: 20 additions & 19 deletions src/submission-handlers/base-handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { EncounterContext } from '../ohri-form-context';
import { OHRIFormField, OpenmrsEncounter, OpenmrsObs, SubmissionHandler } from '../api/types';
import { parseToLocalDateTime } from '../utils/ohri-form-helper';
import { flattenObsList, hasRendering } from '../utils/common-utils';
import { formatDate } from '@openmrs/esm-framework';

// Temporarily holds observations that have already been binded with matching fields
export let assignedObsIds: string[] = [];
Expand Down Expand Up @@ -55,16 +56,16 @@ export const ObsSubmissionHandler: SubmissionHandler = {
assignedObsIds.push(matchedObs[0].obsGroup?.uuid);
}
if (rendering == 'checkbox') {
assignedObsIds.push(...matchedObs.map((obs) => obs.uuid));
assignedObsIds.push(...matchedObs.map(obs => obs.uuid));
field.value = matchedObs;
return field.value.map((o) => o.value.uuid);
return field.value.map(o => o.value.uuid);
}
const obs = matchedObs[0];
field.value = JSON.parse(JSON.stringify(obs));
assignedObsIds.push(obs.uuid);
if (rendering == 'radio' || rendering == 'content-switcher') {
getConcept(field.questionOptions.concept, 'custom:(uuid,display,datatype:(uuid,display,name))').subscribe(
(result) => {
result => {
if (result.datatype.name == 'Boolean') {
field.value.value = obs.value.uuid;
}
Expand All @@ -74,7 +75,7 @@ export const ObsSubmissionHandler: SubmissionHandler = {
if (typeof obs.value == 'string' || typeof obs.value == 'number') {
if (rendering.startsWith('date')) {
const dateObject = parseToLocalDateTime(field.value.value);
field.value.value = dayjs(dateObject).format('YYYY-MM-DD HH:mm');
field.value.value = formatDate(dateObject, { mode: 'wide' });
return dateObject;
}
return obs.value;
Expand All @@ -97,15 +98,15 @@ export const ObsSubmissionHandler: SubmissionHandler = {
}
if (field.questionOptions.rendering == 'checkbox') {
return value.map(
(chosenOption) => field.questionOptions.answers.find((option) => option.concept == chosenOption)?.label,
chosenOption => field.questionOptions.answers.find(option => option.concept == chosenOption)?.label,
);
}
if (rendering == 'content-switcher' || rendering == 'select' || rendering == 'toggle') {
const concept = typeof field.value.value === 'object' ? field.value.value.uuid : field.value.value;
return field.questionOptions.answers.find((option) => option.concept == concept)?.label;
return field.questionOptions.answers.find(option => option.concept == concept)?.label;
}
if (rendering == 'radio') {
return field.questionOptions.answers.find((option) => option.concept == value)?.label;
return field.questionOptions.answers.find(option => option.concept == value)?.label;
}
return value;
},
Expand All @@ -121,13 +122,13 @@ export const ObsSubmissionHandler: SubmissionHandler = {
if (typeof obs.value == 'string' || typeof obs.value == 'number') {
if (rendering == 'date' || rendering == 'datetime') {
const dateObj = parseToLocalDateTime(`${obs.value}`);
return { value: dateObj, display: dayjs(dateObj).format('YYYY-MM-DD HH:mm') };
return { value: dateObj, display: formatDate(dateObj, { mode: 'wide' }) };
}
return { value: obs.value, display: obs.value };
}
return {
value: obs.value?.uuid,
display: field.questionOptions.answers.find((option) => option.concept == obs.value?.uuid)?.label,
display: field.questionOptions.answers.find(option => option.concept == obs.value?.uuid)?.label,
};
}
return null;
Expand Down Expand Up @@ -186,12 +187,12 @@ export const findObsByFormField = (
claimedObsIds: string[],
field: OHRIFormField,
): OpenmrsObs[] => {
const obs = obsList.filter((o) => o.formFieldPath == `ohri-forms-${field.id}`);
const obs = obsList.filter(o => o.formFieldPath == `ohri-forms-${field.id}`);
// We shall fall back to mapping by the associated concept
// That being said, we shall find all matching obs and pick the one that wasn't previously claimed.
if (!obs?.length) {
const obsByConcept = obsList.filter((obs) => obs.concept.uuid == field.questionOptions.concept);
return claimedObsIds?.length ? obsByConcept.filter((obs) => !claimedObsIds.includes(obs.uuid)) : obsByConcept;
const obsByConcept = obsList.filter(obs => obs.concept.uuid == field.questionOptions.concept);
return claimedObsIds?.length ? obsByConcept.filter(obs => !claimedObsIds.includes(obs.uuid)) : obsByConcept;
}
return obs;
};
Expand All @@ -200,8 +201,8 @@ const multiSelectObsHandler = (field: OHRIFormField, values: Array<string>, cont
if (!field.value) {
field.value = [];
}
values.forEach((value) => {
const obs = field.value.find((o) => {
values.forEach(value => {
const obs = field.value.find(o => {
if (typeof o.value == 'string') {
return o.value == value;
}
Expand All @@ -216,9 +217,9 @@ const multiSelectObsHandler = (field: OHRIFormField, values: Array<string>, cont

// void or remove unchecked options
field.questionOptions.answers
.filter((opt) => !values.some((v) => v == opt.concept))
.forEach((opt) => {
const observations = field.value.filter((o) => {
.filter(opt => !values.some(v => v == opt.concept))
.forEach(opt => {
const observations = field.value.filter(o => {
if (typeof o.value == 'string') {
return o.value == opt.concept;
}
Expand All @@ -227,11 +228,11 @@ const multiSelectObsHandler = (field: OHRIFormField, values: Array<string>, cont
if (!observations.length) {
return;
}
observations.forEach((obs) => {
observations.forEach(obs => {
if (context.sessionMode == 'edit' && obs.uuid) {
obs.voided = true;
} else {
field.value = field.value.filter((o) => o.value !== opt.concept);
field.value = field.value.filter(o => o.value !== opt.concept);
}
});
});
Expand Down

0 comments on commit 163481e

Please sign in to comment.