@openmrs/esm-form-entry-app 13.0.2-pre.12995 → 13.0.2-pre.13002

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,247 @@
1
+ import { Injectable } from '@angular/core';
2
+ import { AfeFormControl, ArrayNode, Form, GroupNode, NodeBase, ObsAdapterHelper } from '@openmrs/ngx-formentry';
3
+ import moment from 'moment';
4
+ import { forkJoin, Observable, of, Subject, Subscription } from 'rxjs';
5
+ import { debounceTime, filter, map, startWith, switchMap, take, takeUntil } from 'rxjs/operators';
6
+ import {
7
+ ConceptReferenceRangeResourceService,
8
+ ReferenceRangeContext,
9
+ } from '../openmrs-api/concept-reference-range-resource.service';
10
+ import { getNumericQuestionConcepts, resolveConceptUuid } from '../form-schema/concept-reference-ranges';
11
+ import { ConceptReferenceRange } from '../types';
12
+
13
+ interface NumericNode {
14
+ control: AfeFormControl;
15
+ concept: string;
16
+ context: ReferenceRangeContext;
17
+ }
18
+
19
+ @Injectable({ providedIn: 'root' })
20
+ export class ConceptReferenceRangeFormService {
21
+ private readonly loading = new WeakSet<Form>();
22
+ private readonly loaded = new Subject<Form>();
23
+
24
+ constructor(
25
+ private readonly ranges: ConceptReferenceRangeResourceService,
26
+ private readonly payloads: ObsAdapterHelper,
27
+ ) {}
28
+
29
+ isLoading(form: Form): boolean {
30
+ return this.loading.has(form);
31
+ }
32
+
33
+ whenLoaded(form: Form): Observable<void> {
34
+ return this.isLoading(form)
35
+ ? this.loaded.pipe(
36
+ filter((loadedForm) => loadedForm === form),
37
+ take(1),
38
+ map(() => undefined),
39
+ )
40
+ : of(undefined);
41
+ }
42
+
43
+ connect(form: Form, patientUuid: string): Subscription {
44
+ const subscriptions = new Subscription();
45
+ if (!getNumericQuestionConcepts(form.schema).length) {
46
+ return subscriptions;
47
+ }
48
+ const changes = new Subject<void>();
49
+ const registered = new WeakSet<NodeBase>();
50
+ const requested = new WeakMap<AfeFormControl, string>();
51
+ const encounterDate = form.searchNodeByQuestionId('', 'encounterDatetime')[0];
52
+ const currentMeasurementDate = moment().format();
53
+ const contextOf = (node: NodeBase, ancestors: Array<NodeBase>) =>
54
+ contextFor(
55
+ node,
56
+ ancestors,
57
+ encounterDate,
58
+ form.valueProcessingInfo.encounterUuid,
59
+ currentMeasurementDate,
60
+ this.payloads,
61
+ );
62
+ const refresh = () => {
63
+ this.loading.add(form);
64
+ changes.next();
65
+ };
66
+
67
+ const register = (node: NodeBase, ancestors: Array<NodeBase> = []) => {
68
+ if (!node || registered.has(node)) {
69
+ return;
70
+ }
71
+ registered.add(node);
72
+ const schema = node.question.extras;
73
+ if (schema?.type === 'encounterDatetime' || schema?.questionOptions?.obsField === 'obsDatetime') {
74
+ subscriptions.add(node.control.valueChanges.subscribe(refresh));
75
+ }
76
+ if (isNumeric(node)) {
77
+ // Editing the answer or anything else in its obs group decides whether it's sent with the
78
+ // encounter, which can change the date it's saved with.
79
+ subscriptions.add(
80
+ payloadRoot(node, ancestors).control.valueChanges.subscribe(() => {
81
+ const context = requested.get(node.control);
82
+ if (context !== undefined && context !== JSON.stringify(contextOf(node, ancestors))) {
83
+ refresh();
84
+ }
85
+ }),
86
+ );
87
+ }
88
+ if (node instanceof ArrayNode) {
89
+ node.addChildNodeCreatedListener((child: GroupNode) => {
90
+ if (!subscriptions.closed) {
91
+ register(child, [...ancestors, node]);
92
+ refresh();
93
+ }
94
+ });
95
+ }
96
+ childrenOf(node).forEach((child) => register(child, [...ancestors, node]));
97
+ };
98
+ register(form.rootNode);
99
+ this.loading.add(form);
100
+
101
+ subscriptions.add(
102
+ changes
103
+ .pipe(
104
+ startWith(undefined),
105
+ debounceTime(0),
106
+ switchMap(() => {
107
+ const controls: Array<AfeFormControl> = [];
108
+ const groups = new Map<string, Array<NumericNode>>();
109
+ const collect = (node: NodeBase, ancestors: Array<NodeBase> = []) => {
110
+ if (isNumeric(node)) {
111
+ controls.push(node.control);
112
+ const concept = resolveConceptUuid(form.schema, node.question.extras?.questionOptions?.concept);
113
+ if (concept) {
114
+ const context = contextOf(node, ancestors);
115
+ const key = JSON.stringify(context);
116
+ requested.set(node.control, key);
117
+ const nodes = groups.get(key) ?? [];
118
+ nodes.push({ control: node.control, concept, context });
119
+ groups.set(key, nodes);
120
+ }
121
+ }
122
+ childrenOf(node).forEach((child) => collect(child, [...ancestors, node]));
123
+ };
124
+ collect(form.rootNode);
125
+
126
+ const requests = Array.from(groups.values()).map((nodes) =>
127
+ this.ranges
128
+ .getConceptReferenceRanges(
129
+ patientUuid,
130
+ Array.from(new Set(nodes.map(({ concept }) => concept))),
131
+ nodes[0].context,
132
+ )
133
+ .pipe(map((ranges) => ({ nodes, ranges }))),
134
+ );
135
+ // Cancel stale requests immediately, before the debounced refresh starts.
136
+ return (requests.length ? forkJoin(requests).pipe(takeUntil(changes)) : of([])).pipe(
137
+ map((loadedGroups) => ({ controls, loadedGroups })),
138
+ );
139
+ }),
140
+ )
141
+ .subscribe(({ controls, loadedGroups }) => {
142
+ // Current ranges stay in place until their replacements arrive, so warnings don't flicker.
143
+ const rangeByControl = new Map<AfeFormControl, ConceptReferenceRange | undefined>();
144
+ controls.forEach((control) => rangeByControl.set(control, undefined));
145
+ for (const { nodes, ranges } of loadedGroups) {
146
+ for (const { control, concept } of nodes) {
147
+ rangeByControl.set(control, ranges.get(concept));
148
+ }
149
+ }
150
+ for (const [control, range] of rangeByControl) {
151
+ control.conceptReferenceRange = range;
152
+ control.updateValueAndValidity({ emitEvent: false });
153
+ control.updateAlert();
154
+ }
155
+ form.rootNode.control.updateValueAndValidity({ emitEvent: false });
156
+ this.loading.delete(form);
157
+ this.loaded.next(form);
158
+ }),
159
+ );
160
+ subscriptions.add(() => {
161
+ changes.complete();
162
+ this.loading.delete(form);
163
+ });
164
+ return subscriptions;
165
+ }
166
+ }
167
+
168
+ function childrenOf(node: NodeBase): Array<NodeBase> {
169
+ return Array.isArray(node.children) ? node.children : Object.values(node.children ?? {});
170
+ }
171
+
172
+ function isNumeric(node: NodeBase): node is NodeBase & { control: AfeFormControl } {
173
+ return node.control instanceof AfeFormControl && ['number', 'decimal'].includes(node.question.renderingType);
174
+ }
175
+
176
+ /**
177
+ * Returns the node whose payload carries the answer: the outermost obs group around it, which the obs
178
+ * adapter sends with all of its members as soon as any of them changes, or the answer itself.
179
+ */
180
+ function payloadRoot(node: NodeBase, ancestors: Array<NodeBase>): NodeBase {
181
+ return (
182
+ ancestors.find(
183
+ (ancestor) =>
184
+ ancestor instanceof GroupNode && ['obsGroup', 'complex-obs'].includes(ancestor.question.extras?.type),
185
+ ) ?? node
186
+ );
187
+ }
188
+
189
+ /**
190
+ * Returns the context for the date the answer will be saved with, which depends on whether the
191
+ * answer is sent with the encounter.
192
+ */
193
+ function contextFor(
194
+ node: NodeBase,
195
+ ancestors: Array<NodeBase>,
196
+ encounterDate: NodeBase | undefined,
197
+ encounterUuid: string | undefined,
198
+ currentMeasurementDate: string,
199
+ payloads: ObsAdapterHelper,
200
+ ): ReferenceRangeContext {
201
+ const observation = node.initialValue as { uuid?: string; obsDatetime?: string } | undefined;
202
+ const parent = ancestors[ancestors.length - 1];
203
+ const complexObs = parent?.question.extras?.type === 'complex-obs' ? parent : undefined;
204
+ const savedEncounterDate = validDate(encounterDate?.initialValue);
205
+ const sent: { voided?: boolean } | undefined = payloads.getObsNodePayload(payloadRoot(node, ancestors))[0];
206
+
207
+ let date: string | undefined;
208
+ if (observation?.uuid && (!sent || sent.voided)) {
209
+ // REST only applies an encounter date change to the observations sent with the encounter, so a
210
+ // saved answer that isn't sent keeps its date.
211
+ date = validDate(observation.obsDatetime);
212
+ } else {
213
+ // Core gives an observation sent without a date the encounter date, and moves one sent with the
214
+ // saved encounter date to the new encounter date.
215
+ const ownDate =
216
+ validDate(
217
+ complexObs
218
+ ? childrenOf(complexObs).find((child) => child.question.extras?.questionOptions?.obsField === 'obsDatetime')
219
+ ?.control.value
220
+ : undefined,
221
+ ) ?? validDate(observation?.obsDatetime);
222
+ date =
223
+ ownDate && !(savedEncounterDate && moment(ownDate).isSame(savedEncounterDate))
224
+ ? ownDate
225
+ : validDate(encounterDate?.control.value);
226
+ }
227
+
228
+ if (!date) {
229
+ // A payload without an encounter date leaves an existing encounter's saved date in place, and
230
+ // REST gives a new encounter the time of the save.
231
+ if (encounterUuid) {
232
+ return { encounter: encounterUuid };
233
+ }
234
+ date = currentMeasurementDate;
235
+ }
236
+ if (encounterUuid && savedEncounterDate && moment(savedEncounterDate).isSame(date)) {
237
+ return { encounter: encounterUuid };
238
+ }
239
+ if (observation?.uuid && observation.obsDatetime && moment(observation.obsDatetime).isSame(date)) {
240
+ return { obs: observation.uuid };
241
+ }
242
+ return { date };
243
+ }
244
+
245
+ function validDate(value: moment.MomentInput): string | undefined {
246
+ return value && moment(value).isValid() ? moment(value).format() : undefined;
247
+ }
@@ -134,122 +134,6 @@ describe('Service: FormCreationService', () => {
134
134
  });
135
135
  });
136
136
 
137
- describe('Service: FormCreationService, concept reference ranges', () => {
138
- const session: any = {
139
- sessionLocation: { uuid: 'location-uuid' },
140
- currentProvider: { uuid: 'provider-uuid' },
141
- };
142
-
143
- function buildSchema() {
144
- return {
145
- uuid: 'form-uuid',
146
- display: 'Vitals',
147
- encounterType: { uuid: 'type-uuid', display: 'Vitals' },
148
- pages: [
149
- {
150
- label: 'Vitals',
151
- sections: [
152
- {
153
- label: 'Vitals',
154
- isExpanded: 'true',
155
- questions: [
156
- {
157
- label: 'Temperature',
158
- id: 'temperature',
159
- type: 'obs',
160
- questionOptions: { rendering: 'number', concept: 'temperature-uuid' },
161
- },
162
- ],
163
- },
164
- ],
165
- },
166
- ],
167
- } as any;
168
- }
169
-
170
- beforeEach(() => {
171
- TestBed.configureTestingModule({
172
- providers: [
173
- provideHttpClient(),
174
- provideHttpClientTesting(),
175
- FormCreationService,
176
- SingleSpaPropsService,
177
- {
178
- provide: FormDataSourceService,
179
- useValue: {
180
- getDataSources: () => ({
181
- location: {},
182
- provider: {},
183
- drug: {},
184
- problem: {},
185
- conceptAnswers: {},
186
- diagnoses: {},
187
- recentObs: () => Promise.resolve({}),
188
- }),
189
- getPatientObject: () => ({}),
190
- },
191
- },
192
- { provide: MonthlyScheduleResourceService, useValue: {} },
193
- {
194
- provide: ConfigResourceService,
195
- useValue: { getConfig: () => ({ dataSources: {}, customDataSources: [] }) },
196
- },
197
- ],
198
- imports: [FormEntryModule, TranslateModule.forRoot()],
199
- });
200
-
201
- singleSpaPropsSubject.next({
202
- patient: { id: 'patient-uuid' },
203
- patientUuid: 'patient-uuid',
204
- formUuid: 'form-uuid',
205
- } as any);
206
- });
207
-
208
- afterEach(() => {
209
- TestBed.resetTestingModule();
210
- });
211
-
212
- it('should reject values outside of the reference range which applies to the patient', async () => {
213
- const service: FormCreationService = TestBed.inject(FormCreationService);
214
-
215
- const form = await service.initAndCreateForm({
216
- formSchema: buildSchema(),
217
- session,
218
- patientIdentifiers: [],
219
- conceptReferenceRanges: new Map([
220
- ['temperature-uuid', { uuid: 'range-uuid', concept: 'temperature-uuid', lowAbsolute: 25, hiAbsolute: 43 }],
221
- ]),
222
- });
223
-
224
- const control = form.searchNodeByQuestionId('temperature')[0].control;
225
-
226
- control.setValue(50);
227
- expect(control.valid).toBe(false);
228
-
229
- control.setValue(20);
230
- expect(control.valid).toBe(false);
231
-
232
- control.setValue(37);
233
- expect(control.valid).toBe(true);
234
- });
235
-
236
- it('should leave the question unconstrained when the patient has no reference range', async () => {
237
- const service: FormCreationService = TestBed.inject(FormCreationService);
238
-
239
- const form = await service.initAndCreateForm({
240
- formSchema: buildSchema(),
241
- session,
242
- patientIdentifiers: [],
243
- conceptReferenceRanges: new Map(),
244
- });
245
-
246
- const control = form.searchNodeByQuestionId('temperature')[0].control;
247
-
248
- control.setValue(50);
249
- expect(control.valid).toBe(true);
250
- });
251
- });
252
-
253
137
  describe('Service: FormCreationService, z-score references', () => {
254
138
  const session: any = {
255
139
  sessionLocation: { uuid: 'location-uuid' },
@@ -12,8 +12,7 @@ import {
12
12
  } from '@openmrs/ngx-formentry';
13
13
  import { Session } from '@openmrs/esm-framework';
14
14
  import { ConfigResourceService } from '../services/config-resource.service';
15
- import { ConceptReferenceRange, Encounter, FormSchema, Identifier, PreFilledQuestions } from '../types';
16
- import { applyConceptReferenceRanges } from '../form-schema/concept-reference-ranges';
15
+ import { Encounter, FormSchema, Identifier, PreFilledQuestions } from '../types';
17
16
  import { FormDataSourceService } from '../form-data-source/form-data-source.service';
18
17
  import { MonthlyScheduleResourceService } from '../services/monthly-scheduled-resource.service';
19
18
  import { SingleSpaPropsService } from '../single-spa-props/single-spa-props.service';
@@ -50,12 +49,6 @@ export interface CreateFormParams {
50
49
  * Pre-filled questions
51
50
  */
52
51
  preFilledQuestions?: PreFilledQuestions;
53
-
54
- /**
55
- * The concept reference ranges which apply to the patient, keyed by concept UUID.
56
- * Used to constrain the numeric questions of the form.
57
- */
58
- conceptReferenceRanges?: Map<string, ConceptReferenceRange>;
59
52
  }
60
53
 
61
54
  const loadedCustomDataSources: Record<string, unknown> = {};
@@ -66,11 +59,10 @@ const loadedCustomDataSources: Record<string, unknown> = {};
66
59
  * by the form engine.
67
60
  * The creation of the form encompasses the following tasks:
68
61
  * 1) Hooking up the data sources used by the form engine.
69
- * 2) Constraining numeric questions to the concept reference ranges which apply to the patient.
70
- * 3) Setting up special node handling.
71
- * 4) Filling the form with either:
72
- * 4.1) default values for new forms (-> create mode).
73
- * 4.2) existing values from an existing encounter (-> edit mode).
62
+ * 2) Setting up special node handling.
63
+ * 3) Filling the form with either:
64
+ * 3.1) default values for new forms (-> create mode).
65
+ * 3.2) existing values from an existing encounter (-> edit mode).
74
66
  */
75
67
  @Injectable()
76
68
  export class FormCreationService {
@@ -93,10 +85,9 @@ export class FormCreationService {
93
85
  * @returns The new {@link Form} instance.
94
86
  */
95
87
  public async initAndCreateForm(createFormParams: CreateFormParams) {
96
- const { formSchema, encounter, patientIdentifiers, conceptReferenceRanges } = createFormParams;
88
+ const { formSchema, encounter, patientIdentifiers } = createFormParams;
97
89
 
98
90
  await this.wireDataSources(createFormParams, formSchema);
99
- applyConceptReferenceRanges(formSchema, conceptReferenceRanges);
100
91
 
101
92
  const form = this.formFactory.createForm(formSchema, this.dataSources.dataSources);
102
93
  this.setUpWHOCascading(form);
@@ -1,5 +1,5 @@
1
- import { ConceptReferenceRange, FormSchema, Questions } from '../types';
2
- import { applyConceptReferenceRanges, getNumericQuestionConcepts } from './concept-reference-ranges';
1
+ import { FormSchema, Questions } from '../types';
2
+ import { getNumericQuestionConcepts } from './concept-reference-ranges';
3
3
 
4
4
  function buildSchema(questions: Array<Partial<Questions>>, conceptReferences?: FormSchema['conceptReferences']) {
5
5
  return {
@@ -21,12 +21,6 @@ function buildSchema(questions: Array<Partial<Questions>>, conceptReferences?: F
21
21
  } as FormSchema;
22
22
  }
23
23
 
24
- function buildReferenceRange(concept: string, referenceRange: Partial<ConceptReferenceRange>) {
25
- return new Map<string, ConceptReferenceRange>([
26
- [concept, { uuid: `${concept}-range`, concept, ...referenceRange } as ConceptReferenceRange],
27
- ]);
28
- }
29
-
30
24
  describe('getNumericQuestionConcepts', () => {
31
25
  it('returns the concepts of the numeric questions only', () => {
32
26
  const schema = buildSchema([
@@ -103,123 +97,3 @@ describe('getNumericQuestionConcepts', () => {
103
97
  expect(getNumericQuestionConcepts(schema)).toEqual(['weight-uuid']);
104
98
  });
105
99
  });
106
-
107
- describe('applyConceptReferenceRanges', () => {
108
- it('applies the absolute bounds of the reference range to a numeric question', () => {
109
- const schema = buildSchema([
110
- { id: 'temperature', type: 'obs', questionOptions: { rendering: 'number', concept: 'temperature-uuid' } as any },
111
- ]);
112
-
113
- applyConceptReferenceRanges(schema, buildReferenceRange('temperature-uuid', { lowAbsolute: 25, hiAbsolute: 43 }));
114
-
115
- expect(schema.pages[0].sections[0].questions[0].questionOptions).toEqual(
116
- jasmine.objectContaining({ min: '25', max: '43' }),
117
- );
118
- });
119
-
120
- it('applies a lower bound of zero, which the schema expresses as a string', () => {
121
- const schema = buildSchema([
122
- { id: 'pulse', type: 'obs', questionOptions: { rendering: 'number', concept: 'pulse-uuid' } as any },
123
- ]);
124
-
125
- applyConceptReferenceRanges(schema, buildReferenceRange('pulse-uuid', { lowAbsolute: 0, hiAbsolute: 230 }));
126
-
127
- expect(schema.pages[0].sections[0].questions[0].questionOptions).toEqual(
128
- jasmine.objectContaining({ min: '0', max: '230' }),
129
- );
130
- });
131
-
132
- it('keeps the stricter of the schema bound and the reference range bound', () => {
133
- const schema = buildSchema([
134
- {
135
- id: 'temperature',
136
- type: 'obs',
137
- questionOptions: { rendering: 'number', concept: 'temperature-uuid', min: '30', max: '50' } as any,
138
- },
139
- ]);
140
-
141
- applyConceptReferenceRanges(schema, buildReferenceRange('temperature-uuid', { lowAbsolute: 25, hiAbsolute: 43 }));
142
-
143
- expect(schema.pages[0].sections[0].questions[0].questionOptions).toEqual(
144
- jasmine.objectContaining({ min: '30', max: '43' }),
145
- );
146
- });
147
-
148
- it('resolves questions which refer to their concept by concept reference', () => {
149
- const schema = buildSchema(
150
- [{ id: 'weight', type: 'obs', questionOptions: { rendering: 'decimal', concept: 'CIEL:5089' } as any }],
151
- { 'CIEL:5089': { uuid: 'weight-uuid', display: 'Weight (kg)' } },
152
- );
153
-
154
- applyConceptReferenceRanges(schema, buildReferenceRange('weight-uuid', { lowAbsolute: 0, hiAbsolute: 250 }));
155
-
156
- expect(schema.pages[0].sections[0].questions[0].questionOptions).toEqual(
157
- jasmine.objectContaining({ min: '0', max: '250' }),
158
- );
159
- });
160
-
161
- it('ignores the normal and critical bounds', () => {
162
- const schema = buildSchema([
163
- { id: 'temperature', type: 'obs', questionOptions: { rendering: 'number', concept: 'temperature-uuid' } as any },
164
- ]);
165
-
166
- applyConceptReferenceRanges(
167
- schema,
168
- buildReferenceRange('temperature-uuid', {
169
- lowNormal: 36,
170
- hiNormal: 37.5,
171
- lowCritical: 35,
172
- hiCritical: 40,
173
- lowAbsolute: 25,
174
- hiAbsolute: 43,
175
- }),
176
- );
177
-
178
- expect(schema.pages[0].sections[0].questions[0].questionOptions).toEqual(
179
- jasmine.objectContaining({ min: '25', max: '43' }),
180
- );
181
- });
182
-
183
- it('leaves a question untouched when only one absolute bound can be determined', () => {
184
- const questionOptions = { rendering: 'number', concept: 'temperature-uuid' } as any;
185
- const schema = buildSchema([{ id: 'temperature', type: 'obs', questionOptions }]);
186
-
187
- applyConceptReferenceRanges(schema, buildReferenceRange('temperature-uuid', { hiAbsolute: 43 }));
188
-
189
- expect(questionOptions.min).toBeUndefined();
190
- expect(questionOptions.max).toBeUndefined();
191
- });
192
-
193
- it('leaves questions whose concept reference does not resolve untouched', () => {
194
- const questionOptions = { rendering: 'number', concept: 'CIEL:00000' } as any;
195
- const schema = buildSchema([{ id: 'stale', type: 'obs', questionOptions }], {
196
- 'CIEL:5089': { uuid: 'weight-uuid', display: 'Weight (kg)' },
197
- });
198
-
199
- applyConceptReferenceRanges(schema, buildReferenceRange('CIEL:00000', { lowAbsolute: 0, hiAbsolute: 230 }));
200
-
201
- expect(questionOptions.min).toBeUndefined();
202
- expect(questionOptions.max).toBeUndefined();
203
- });
204
-
205
- it('leaves questions without a matching reference range untouched', () => {
206
- const questionOptions = { rendering: 'number', concept: 'temperature-uuid' } as any;
207
- const schema = buildSchema([{ id: 'temperature', type: 'obs', questionOptions }]);
208
-
209
- applyConceptReferenceRanges(schema, buildReferenceRange('pulse-uuid', { lowAbsolute: 0, hiAbsolute: 230 }));
210
-
211
- expect(questionOptions.min).toBeUndefined();
212
- expect(questionOptions.max).toBeUndefined();
213
- });
214
-
215
- it('does nothing when there are no reference ranges', () => {
216
- const questionOptions = { rendering: 'number', concept: 'temperature-uuid', max: '50' } as any;
217
- const schema = buildSchema([{ id: 'temperature', type: 'obs', questionOptions }]);
218
-
219
- applyConceptReferenceRanges(schema, new Map());
220
- applyConceptReferenceRanges(schema, undefined);
221
-
222
- expect(questionOptions.min).toBeUndefined();
223
- expect(questionOptions.max).toBe('50');
224
- });
225
- });
@@ -1,10 +1,9 @@
1
- import { ConceptReferenceRange, FormSchema, Questions } from '../types';
1
+ import { FormSchema, Questions } from '../types';
2
2
 
3
3
  /**
4
- * The form engine only derives numeric bounds from `questionOptions.min` and `questionOptions.max`,
5
- * and only does so for these two rendering types.
4
+ * Rendering types supported by the form engine for numeric observations.
6
5
  */
7
- const numericRenderingTypes = ['number', 'decimal'];
6
+ const numericRenderingTypes = ['number', 'decimal', 'numeric'];
8
7
 
9
8
  /**
10
9
  * Collects the concept of every numeric question in the given schema. These are the concepts for
@@ -22,46 +21,6 @@ export function getNumericQuestionConcepts(formSchema: FormSchema): Array<string
22
21
  return Array.from(new Set(concepts));
23
22
  }
24
23
 
25
- /**
26
- * Narrows the bounds of every numeric question to the concept reference range which applies to the
27
- * current patient, so that values the backend would reject are caught during data entry.
28
- *
29
- * Only the absolute bounds are used, mirroring how the backend validates observations. A bound
30
- * defined by the schema is never widened: whichever of the two bounds is stricter wins.
31
- *
32
- * @param formSchema The schema to be modified in place.
33
- * @param referenceRanges The reference ranges which apply to the patient, keyed by concept UUID.
34
- */
35
- export function applyConceptReferenceRanges(
36
- formSchema: FormSchema,
37
- referenceRanges: Map<string, ConceptReferenceRange> | undefined,
38
- ) {
39
- if (!referenceRanges?.size) {
40
- return;
41
- }
42
-
43
- for (const question of getNumericQuestions(formSchema)) {
44
- const concept = resolveConceptUuid(formSchema, question.questionOptions.concept);
45
- const referenceRange = concept ? referenceRanges.get(concept) : undefined;
46
-
47
- if (!referenceRange) {
48
- continue;
49
- }
50
-
51
- const min = strictestBound(toNumber(question.questionOptions.min), toNumber(referenceRange.lowAbsolute), Math.max);
52
- const max = strictestBound(toNumber(question.questionOptions.max), toNumber(referenceRange.hiAbsolute), Math.min);
53
-
54
- // The form engine only wires up the min and max validators when both bounds are set, so there
55
- // is nothing to apply as long as one of them is missing.
56
- if (min === undefined || max === undefined) {
57
- continue;
58
- }
59
-
60
- question.questionOptions.min = String(min);
61
- question.questionOptions.max = String(max);
62
- }
63
- }
64
-
65
24
  function getNumericQuestions(formSchema: FormSchema): Array<Questions> {
66
25
  const numericQuestions: Array<Questions> = [];
67
26
 
@@ -92,7 +51,7 @@ function getNumericQuestions(formSchema: FormSchema): Array<Questions> {
92
51
  * question uses, so a missing key means the reference is stale. Returning nothing for those is how a
93
52
  * stale question ends up being left out of the request instead of taking a whole batch down.
94
53
  */
95
- function resolveConceptUuid(formSchema: FormSchema, concept: string): string | undefined {
54
+ export function resolveConceptUuid(formSchema: FormSchema, concept: string): string | undefined {
96
55
  const conceptReferences = formSchema.conceptReferences;
97
56
 
98
57
  if (conceptReferences) {
@@ -101,28 +60,3 @@ function resolveConceptUuid(formSchema: FormSchema, concept: string): string | u
101
60
 
102
61
  return concept;
103
62
  }
104
-
105
- function toNumber(value: string | number | null | undefined): number | undefined {
106
- if (value === null || value === undefined || value === '') {
107
- return undefined;
108
- }
109
-
110
- const parsed = Number(value);
111
- return Number.isFinite(parsed) ? parsed : undefined;
112
- }
113
-
114
- function strictestBound(
115
- schemaBound: number | undefined,
116
- referenceRangeBound: number | undefined,
117
- pickStrictest: (a: number, b: number) => number,
118
- ): number | undefined {
119
- if (schemaBound === undefined) {
120
- return referenceRangeBound;
121
- }
122
-
123
- if (referenceRangeBound === undefined) {
124
- return schemaBound;
125
- }
126
-
127
- return pickStrictest(schemaBound, referenceRangeBound);
128
- }
@@ -63,6 +63,21 @@ describe('Service: ConceptReferenceRangeResourceService', () => {
63
63
  httpMock.expectNone(() => true);
64
64
  });
65
65
 
66
+ [{ date: '2020-01-01T00:00:00Z' }, { encounter: 'encounter-uuid' }, { obs: 'observation-uuid' }].forEach(
67
+ (context) => {
68
+ it(`passes the measurement context to the backend (${JSON.stringify(context)})`, (done) => {
69
+ conceptReferenceRangeResourceService
70
+ .getConceptReferenceRanges('patient-uuid', ['temperature-uuid'], context)
71
+ .subscribe(() => done());
72
+ const request = httpMock.expectOne((req) => req.url === conceptReferenceRangeResourceService.getUrl());
73
+ for (const [key, value] of Object.entries(context)) {
74
+ expect(request.request.params.get(key)).toBe(value);
75
+ }
76
+ request.flush({ results: [] });
77
+ });
78
+ },
79
+ );
80
+
66
81
  it('should follow the next link until the backend runs out of pages', (done) => {
67
82
  conceptReferenceRangeResourceService
68
83
  .getConceptReferenceRanges('patient-uuid', ['temperature-uuid', 'pulse-uuid'])