@ovok/core 0.4.49-rc.4 → 0.4.49-rc.5

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.
Files changed (47) hide show
  1. package/dist/client/observation/bundle-entry-status.d.ts +3 -0
  2. package/dist/client/observation/bundle-entry-status.js +13 -0
  3. package/dist/client/observation/fhir-systems.d.ts +7 -0
  4. package/dist/client/observation/fhir-systems.js +8 -1
  5. package/dist/client/observation/methods/generateObservationBodiesByMeasurement.js +7 -65
  6. package/dist/client/observation/methods/observationsToMeasurements.js +64 -11
  7. package/dist/client/observation/observation-bundle-utils.d.ts +5 -7
  8. package/dist/client/observation/observation-bundle-utils.js +55 -71
  9. package/dist/client/observation/observation-coding.d.ts +12 -0
  10. package/dist/client/observation/observation-coding.js +69 -0
  11. package/dist/client/observation/observation-groups.d.ts +12 -0
  12. package/dist/client/observation/observation-groups.js +51 -0
  13. package/dist/client/observation/reading-group-backfill.d.ts +13 -0
  14. package/dist/client/observation/reading-group-backfill.js +79 -0
  15. package/dist/client/observation/reading-group.d.ts +14 -0
  16. package/dist/client/observation/reading-group.js +85 -0
  17. package/dist/client/observation/series.d.ts +3 -2
  18. package/dist/client/observation/series.js +10 -4
  19. package/dist/client/observation/services/base-observation-service.d.ts +1 -1
  20. package/dist/client/observation/services/base-observation-service.js +6 -12
  21. package/dist/client/observation/services/blood-pressure.d.ts +2 -0
  22. package/dist/client/observation/services/blood-pressure.js +9 -5
  23. package/dist/client/observation/services/component-observation-services.js +2 -2
  24. package/dist/client/observation/services/ecg-observation-fragments.d.ts +4 -0
  25. package/dist/client/observation/services/ecg-observation-fragments.js +30 -37
  26. package/dist/client/observation/services/ecg.d.ts +3 -1
  27. package/dist/client/observation/services/ecg.js +19 -19
  28. package/dist/client/observation/services/uric-acid-service.js +2 -12
  29. package/dist/client/observation/services/urine-analyte-values.d.ts +4 -0
  30. package/dist/client/observation/services/urine-analyte-values.js +27 -0
  31. package/dist/client/observation/types/UrineAnalytes.d.ts +15 -0
  32. package/dist/client/observation/types/UrineAnalytes.js +17 -9
  33. package/dist/client/observation/utils/getDeviceObject.js +15 -32
  34. package/dist/client/offline/offline-measurement-queue.js +2 -8
  35. package/dist/client/ovok-client.d.ts +1 -0
  36. package/dist/client/ovok-client.js +11 -6
  37. package/dist/conformance/capability-requirements.js +1 -1
  38. package/dist/hooks/observation-hooks.d.ts +2 -1
  39. package/dist/hooks/observation-hooks.js +4 -3
  40. package/dist/next/resources/measurements/measurements-resource.d.ts +11 -2
  41. package/dist/next/resources/measurements/measurements-resource.js +31 -6
  42. package/dist/next/resources/measurements/observation-builder.d.ts +1 -1
  43. package/dist/next/resources/measurements/observation-builder.js +16 -7
  44. package/dist/next/resources/measurements/save-error.js +3 -4
  45. package/dist/next/resources/realtime/realtime-socket.js +12 -5
  46. package/dist/next/resources/realtime/realtime-types.d.ts +3 -1
  47. package/package.json +2 -2
@@ -0,0 +1,3 @@
1
+ import { BundleEntry } from "@medplum/fhirtypes";
2
+ /** An entry the server refused or failed on. */
3
+ export declare const isFailedEntry: (entry: BundleEntry) => boolean;
@@ -0,0 +1,13 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.isFailedEntry = void 0;
4
+ const MULTIPLE_MATCHES = "multiple-matches";
5
+ /** A conditional create that matched several saved copies of the observation: it is saved already. */
6
+ const matchedSeveralCopies = (entry) => { var _a, _b, _c, _d; return (_d = (_c = (_b = (_a = entry.response) === null || _a === void 0 ? void 0 : _a.outcome) === null || _b === void 0 ? void 0 : _b.issue) === null || _c === void 0 ? void 0 : _c.some((issue) => issue.code === MULTIPLE_MATCHES)) !== null && _d !== void 0 ? _d : false; };
7
+ /** An entry the server refused or failed on. */
8
+ const isFailedEntry = (entry) => {
9
+ var _a, _b;
10
+ const status = (_b = (_a = entry.response) === null || _a === void 0 ? void 0 : _a.status) !== null && _b !== void 0 ? _b : "";
11
+ return (status.startsWith("4") || status.startsWith("5")) && !matchedSeveralCopies(entry);
12
+ };
13
+ exports.isFailedEntry = isFailedEntry;
@@ -1,4 +1,11 @@
1
1
  export declare const LOINC_SYSTEM = "http://loinc.org";
2
2
  export declare const UCUM_SYSTEM = "http://unitsofmeasure.org";
3
+ export declare const SNOMED_SYSTEM = "http://snomed.info/sct";
4
+ /** ISO/IEEE 11073-10101 nomenclature, which codes waveforms such as MDC_ECG_ELEC_POTL. */
5
+ export declare const MDC_SYSTEM = "urn:oid:2.16.840.1.113883.6.24";
6
+ /** Ovok's own codes for a measurement type, used where no standard code fits. */
7
+ export declare const MEASUREMENT_TYPE_SYSTEM = "https://sdk.ovok.com/fhir/CodeSystem/measurement-type";
8
+ export declare const OBSERVATION_CATEGORY_SYSTEM = "http://terminology.hl7.org/CodeSystem/observation-category";
3
9
  /** Identifier system of the device-side reading id that makes a save idempotent. */
4
10
  export declare const DEVICE_READING_IDENTIFIER_SYSTEM = "https://api.ovok.com/fhir/StructureDefinition/device-reading-id";
11
+ export declare const OVOK_EXTENSION_BASE_URL = "http://ovok.com/fhir/StructureDefinition";
@@ -1,7 +1,14 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.DEVICE_READING_IDENTIFIER_SYSTEM = exports.UCUM_SYSTEM = exports.LOINC_SYSTEM = void 0;
3
+ exports.OVOK_EXTENSION_BASE_URL = exports.DEVICE_READING_IDENTIFIER_SYSTEM = exports.OBSERVATION_CATEGORY_SYSTEM = exports.MEASUREMENT_TYPE_SYSTEM = exports.MDC_SYSTEM = exports.SNOMED_SYSTEM = exports.UCUM_SYSTEM = exports.LOINC_SYSTEM = void 0;
4
4
  exports.LOINC_SYSTEM = "http://loinc.org";
5
5
  exports.UCUM_SYSTEM = "http://unitsofmeasure.org";
6
+ exports.SNOMED_SYSTEM = "http://snomed.info/sct";
7
+ /** ISO/IEEE 11073-10101 nomenclature, which codes waveforms such as MDC_ECG_ELEC_POTL. */
8
+ exports.MDC_SYSTEM = "urn:oid:2.16.840.1.113883.6.24";
9
+ /** Ovok's own codes for a measurement type, used where no standard code fits. */
10
+ exports.MEASUREMENT_TYPE_SYSTEM = "https://sdk.ovok.com/fhir/CodeSystem/measurement-type";
11
+ exports.OBSERVATION_CATEGORY_SYSTEM = "http://terminology.hl7.org/CodeSystem/observation-category";
6
12
  /** Identifier system of the device-side reading id that makes a save idempotent. */
7
13
  exports.DEVICE_READING_IDENTIFIER_SYSTEM = "https://api.ovok.com/fhir/StructureDefinition/device-reading-id";
14
+ exports.OVOK_EXTENSION_BASE_URL = "http://ovok.com/fhir/StructureDefinition";
@@ -2,79 +2,21 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.generateObservationBodiesByMeasurement = generateObservationBodiesByMeasurement;
4
4
  const core_1 = require("@medplum/core");
5
- const fhir_systems_1 = require("../fhir-systems");
6
- const creator_1 = require("../services/creator");
7
- const getDeviceObject_1 = require("../utils/getDeviceObject");
5
+ const observation_builder_1 = require("../../../next/resources/measurements/observation-builder");
8
6
  const getPatientReference = async (client, patientId) => {
9
7
  if (patientId) {
10
8
  return `Patient/${patientId}`;
11
9
  }
12
10
  const profile = (await client.getProfileAsync());
13
- return (0, core_1.getReferenceString)(profile);
11
+ const reference = profile && (0, core_1.getReferenceString)(profile);
12
+ if (!reference) {
13
+ throw new Error("Sign in before building observations for the signed-in profile.");
14
+ }
15
+ return reference;
14
16
  };
15
- const addSourceIdentifier = (observations, patientReference, sourceId) => patientReference && sourceId
16
- ? observations.map((observation, index) => {
17
- var _a;
18
- return ({
19
- ...observation,
20
- identifier: [
21
- ...((_a = observation.identifier) !== null && _a !== void 0 ? _a : []),
22
- {
23
- system: fhir_systems_1.DEVICE_READING_IDENTIFIER_SYSTEM,
24
- value: `${patientReference}/${sourceId}/${index}`,
25
- },
26
- ],
27
- });
28
- })
29
- : observations;
30
17
  /**
31
18
  * Builds the FHIR Observations that represent a measurement, without saving them.
32
19
  */
33
20
  async function generateObservationBodiesByMeasurement(params) {
34
- var _a, _b;
35
- const { device, measurement } = params;
36
- const measurementTypeKey = measurement.measurementTypeKey;
37
- const patientReference = await getPatientReference(this, params.patientId);
38
- const observationService = creator_1.ObservationServiceCreator.getInstance().getService(measurementTypeKey);
39
- const deviceObject = (0, getDeviceObject_1.getDeviceObject)(device);
40
- const applyEffectiveDateTime = (observation) => params.effectiveDateTime && !observation.effectivePeriod
41
- ? {
42
- ...observation,
43
- effectiveDateTime: params.effectiveDateTime.toISOString(),
44
- }
45
- : observation;
46
- const fragments = (_b = (_a = observationService.generateObservationFragments) === null || _a === void 0 ? void 0 : _a.call(observationService, measurement)) !== null && _b !== void 0 ? _b : codeValueFragments(observationService, measurement);
47
- const observations = fragments
48
- .map((fragment) => ({
49
- resourceType: "Observation",
50
- status: "registered",
51
- subject: {
52
- reference: patientReference,
53
- },
54
- device: deviceObject,
55
- ...fragment.value,
56
- code: fragment.code,
57
- ...(fragment.additionalProperties || {}),
58
- }))
59
- .filter(hasObservationValue)
60
- .map(applyEffectiveDateTime);
61
- return addSourceIdentifier(observations, patientReference, params.sourceId);
21
+ return (0, observation_builder_1.buildObservations)(params, await getPatientReference(this, params.patientId));
62
22
  }
63
- /** Services without fragments describe their observations as parallel code, value and property lists. */
64
- const codeValueFragments = (service, measurement) => {
65
- const codes = service.getObservationCodes();
66
- const values = service.generateValues(measurement);
67
- const additionalProperties = service.getAdditionalProperties(measurement);
68
- return codes.map((code, index) => ({
69
- code,
70
- value: values[index],
71
- additionalProperties: additionalProperties[index],
72
- }));
73
- };
74
- const hasObservationValue = (observation) => {
75
- var _a, _b, _c, _d, _e, _f;
76
- return ((_a = observation.valueQuantity) === null || _a === void 0 ? void 0 : _a.value) !== undefined ||
77
- Boolean((_b = observation.valueSampledData) === null || _b === void 0 ? void 0 : _b.data) ||
78
- Boolean((_e = (_d = (_c = observation.valueCodeableConcept) === null || _c === void 0 ? void 0 : _c.coding) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.code) ||
79
- Boolean((_f = observation.component) === null || _f === void 0 ? void 0 : _f.length);
80
- };
@@ -4,15 +4,22 @@ Object.defineProperty(exports, "__esModule", { value: true });
4
4
  exports.observationsToMeasurements = exports.observationCodesForTypes = void 0;
5
5
  const MeasurementTypes_1 = require("../../../types/MeasurementTypes");
6
6
  const fhir_systems_1 = require("../fhir-systems");
7
+ const observation_coding_1 = require("../observation-coding");
8
+ const reading_group_1 = require("../reading-group");
9
+ const blood_pressure_1 = require("../services/blood-pressure");
7
10
  const single_value_services_1 = require("../services/single-value-services");
8
11
  const DEFAULT_OBSERVATION_TIME_TOLERANCE_MS = 1000;
9
12
  const codeOf = (observation) => {
10
13
  var _a, _b, _c, _d, _e, _f, _g;
11
14
  return (_d = (_c = (_b = (_a = observation.code) === null || _a === void 0 ? void 0 : _a.coding) === null || _b === void 0 ? void 0 : _b.find((coding) => coding.system === fhir_systems_1.LOINC_SYSTEM)) === null || _c === void 0 ? void 0 : _c.code) !== null && _d !== void 0 ? _d : (_g = (_f = (_e = observation.code) === null || _e === void 0 ? void 0 : _e.coding) === null || _f === void 0 ? void 0 : _f[0]) === null || _g === void 0 ? void 0 : _g.code;
12
15
  };
16
+ const PRESENCE_VALUES = {
17
+ [MeasurementTypes_1.UrinePresenceCoding.positive]: 1,
18
+ [MeasurementTypes_1.UrinePresenceCoding.negative]: 0,
19
+ };
13
20
  const valueOf = (observation) => {
14
- var _a;
15
- const value = (_a = observation.valueQuantity) === null || _a === void 0 ? void 0 : _a.value;
21
+ var _a, _b, _c, _d, _e, _f;
22
+ const value = (_b = (_a = observation.valueQuantity) === null || _a === void 0 ? void 0 : _a.value) !== null && _b !== void 0 ? _b : PRESENCE_VALUES[(_f = (_e = (_d = (_c = observation.valueCodeableConcept) === null || _c === void 0 ? void 0 : _c.coding) === null || _d === void 0 ? void 0 : _d.find((coding) => coding.system === MeasurementTypes_1.UrinePresenceCoding.system)) === null || _e === void 0 ? void 0 : _e.code) !== null && _f !== void 0 ? _f : ""];
16
23
  return typeof value === "number" ? value : undefined;
17
24
  };
18
25
  const irregularHeartbeatOf = (observations) => {
@@ -30,6 +37,13 @@ const irregularHeartbeatOf = (observations) => {
30
37
  }
31
38
  return result === MeasurementTypes_1.PulseRhythmCoding.regular ? false : undefined;
32
39
  };
40
+ const bloodPressureStatusOf = (observations) => {
41
+ var _a;
42
+ const status = (_a = observations
43
+ .flatMap((observation) => { var _a; return (_a = observation.extension) !== null && _a !== void 0 ? _a : []; })
44
+ .find((extension) => extension.url === blood_pressure_1.BLOOD_PRESSURE_STATUS_URL)) === null || _a === void 0 ? void 0 : _a.valueString;
45
+ return status ? { status: status } : {};
46
+ };
33
47
  const recordedAtOf = (observation) => {
34
48
  var _a, _b;
35
49
  const value = (_a = observation.effectiveDateTime) !== null && _a !== void 0 ? _a : (_b = observation.effectivePeriod) === null || _b === void 0 ? void 0 : _b.start;
@@ -45,6 +59,13 @@ const groupKey = (observation) => {
45
59
  const recordingId = ((_b = observation.hasMember) === null || _b === void 0 ? void 0 : _b.length) ? id.replace(/-\d+$/, "") : id;
46
60
  return recordingId || ((_c = recordedAtOf(observation)) === null || _c === void 0 ? void 0 : _c.toISOString()) || "unknown";
47
61
  };
62
+ /** A recording id the SDK assigns before saving; older saves kept it in `hasMember`, where it matches nothing. */
63
+ const UNSAVED_RECORDING_ID = /^ecg-\d+-\d+$/;
64
+ /** The id of the first observation a later segment or the heart rate points at. */
65
+ const mainIdOf = (observation) => {
66
+ var _a;
67
+ return (_a = observation.hasMember) === null || _a === void 0 ? void 0 : _a.map((member) => { var _a, _b; return (_b = (_a = member.reference) === null || _a === void 0 ? void 0 : _a.match(/^Observation\/(.+)$/)) === null || _b === void 0 ? void 0 : _b[1]; }).find(Boolean);
68
+ };
48
69
  const ecgGroupKey = (observation, observations) => {
49
70
  const parent = observations.find((candidate) => candidate.id &&
50
71
  observation.id &&
@@ -53,6 +74,10 @@ const ecgGroupKey = (observation, observations) => {
53
74
  if (parent) {
54
75
  return groupKey(parent);
55
76
  }
77
+ const mainId = mainIdOf(observation);
78
+ if (mainId && !UNSAVED_RECORDING_ID.test(mainId)) {
79
+ return mainId;
80
+ }
56
81
  if (codeOf(observation) === MeasurementTypes_1.ObservationCode.ECG) {
57
82
  return groupKey(observation);
58
83
  }
@@ -201,9 +226,17 @@ const groupObservations = (observations, options, legacyKey) => {
201
226
  }
202
227
  return [...groups.values()].sort((left, right) => left.firstIndex - right.firstIndex);
203
228
  };
229
+ /** A value by its code: from the observation that holds it, else from a group that repeats it as a component. */
204
230
  const firstValue = (observations, code) => {
205
231
  const match = observations.find((observation) => codeOf(observation) === code);
206
- return match ? valueOf(match) : undefined;
232
+ return match ? valueOf(match) : groupComponentValue(observations, code);
233
+ };
234
+ const groupComponentValue = (observations, code) => {
235
+ var _a, _b;
236
+ return (_b = (_a = observations
237
+ .filter(reading_group_1.isReadingGroup)
238
+ .flatMap((group) => { var _a; return (_a = group.component) !== null && _a !== void 0 ? _a : []; })
239
+ .find((component) => { var _a, _b; return (_b = (_a = component.code) === null || _a === void 0 ? void 0 : _a.coding) === null || _b === void 0 ? void 0 : _b.some((coding) => coding.code === code); })) === null || _a === void 0 ? void 0 : _a.valueQuantity) === null || _b === void 0 ? void 0 : _b.value;
207
240
  };
208
241
  const LIPID_FIELDS = [
209
242
  { key: "totalCholesterol", codes: [MeasurementTypes_1.ObservationCode.TOTAL_CHOLESTEROL_MASS, MeasurementTypes_1.ObservationCode.TOTAL_CHOLESTEROL_MOLAR] },
@@ -269,13 +302,14 @@ const baseMeasurement = (measurementTypeKey, observation) => ({
269
302
  ...(recordedAtOf(observation) ? { recordedAt: recordedAtOf(observation) } : {}),
270
303
  });
271
304
  const inverseGroup = (type, observations) => {
272
- var _a, _b, _c, _d, _e, _f, _g;
305
+ var _a, _b, _c, _d, _e, _f, _g, _h;
273
306
  const first = [...observations].sort((left, right) => {
274
307
  var _a, _b, _c, _d;
275
308
  return ((_b = (_a = recordedAtOf(left)) === null || _a === void 0 ? void 0 : _a.getTime()) !== null && _b !== void 0 ? _b : Number.MAX_SAFE_INTEGER) -
276
309
  ((_d = (_c = recordedAtOf(right)) === null || _c === void 0 ? void 0 : _c.getTime()) !== null && _d !== void 0 ? _d : Number.MAX_SAFE_INTEGER);
277
310
  })[0];
278
- const measurement = baseMeasurement(type, first);
311
+ const deviceUser = (0, observation_coding_1.deviceUserOf)(observations);
312
+ const measurement = { ...baseMeasurement(type, first), ...(deviceUser === undefined ? {} : { memorySlot: deviceUser }) };
279
313
  const value = (code) => firstValue(observations, code);
280
314
  const single = single_value_services_1.singleValueFields.get(type);
281
315
  if (single) {
@@ -291,6 +325,7 @@ const inverseGroup = (type, observations) => {
291
325
  meanArterialPressure: value(MeasurementTypes_1.ObservationCode.MEAN_BLOOD_PRESSURE),
292
326
  heartRate: value(MeasurementTypes_1.ObservationCode.BLOOD_PRESSURE_HEART_RATE),
293
327
  irregularHeartbeat: irregularHeartbeatOf(observations),
328
+ ...bloodPressureStatusOf(observations),
294
329
  };
295
330
  case MeasurementTypes_1.MeasurementTypeKey.bloodOxygenPulseRate:
296
331
  return {
@@ -317,7 +352,7 @@ const inverseGroup = (type, observations) => {
317
352
  ? observation.valueSampledData.data.split(/\s+/).filter(Boolean).map(Number)
318
353
  : [];
319
354
  });
320
- const diagnosticResult = (_d = (_c = first.interpretation) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.text;
355
+ const diagnosticResult = (_e = (_d = (_c = observations.find((observation) => { var _a, _b; return (_b = (_a = observation.interpretation) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.text; })) === null || _c === void 0 ? void 0 : _c.interpretation) === null || _d === void 0 ? void 0 : _d[0]) === null || _e === void 0 ? void 0 : _e.text;
321
356
  const duration = observations.reduce((total, observation) => {
322
357
  var _a, _b, _c, _d;
323
358
  return total +
@@ -327,7 +362,7 @@ const inverseGroup = (type, observations) => {
327
362
  ...measurement,
328
363
  measurementTypeKey: type,
329
364
  diagramPoints: points,
330
- heartRate: (_e = value(MeasurementTypes_1.ObservationCode.ECG_HEART_RATE)) !== null && _e !== void 0 ? _e : value(MeasurementTypes_1.ObservationCode.HEART_RATE),
365
+ heartRate: (_f = value(MeasurementTypes_1.ObservationCode.ECG_HEART_RATE)) !== null && _f !== void 0 ? _f : value(MeasurementTypes_1.ObservationCode.HEART_RATE),
331
366
  ...(diagnosticResult ? { diagnosticResult } : {}),
332
367
  ...(duration > 0 ? { duration } : {}),
333
368
  };
@@ -342,7 +377,7 @@ const inverseGroup = (type, observations) => {
342
377
  };
343
378
  for (const observation of observations) {
344
379
  const analyteCode = codeOf(observation);
345
- const component = (_g = (_f = first.code) === null || _f === void 0 ? void 0 : _f.coding) === null || _g === void 0 ? void 0 : _g.find((coding) => coding.code === analyteCode);
380
+ const component = (_h = (_g = first.code) === null || _g === void 0 ? void 0 : _g.coding) === null || _h === void 0 ? void 0 : _h.find((coding) => coding.code === analyteCode);
346
381
  const value = valueOf(observation);
347
382
  const key = analyteByCode[analyteCode !== null && analyteCode !== void 0 ? analyteCode : ""];
348
383
  if (key && typeof value === "number") {
@@ -378,17 +413,35 @@ const inverseGroup = (type, observations) => {
378
413
  const COMPONENT_TYPES = new Set([MeasurementTypes_1.MeasurementTypeKey.respiratoryTherapy, MeasurementTypes_1.MeasurementTypeKey.babySleep]);
379
414
  const codesForType = {
380
415
  ...Object.fromEntries([...single_value_services_1.singleValueFields].map(([type, { code }]) => [type, [code]])),
381
- [MeasurementTypes_1.MeasurementTypeKey.bloodPressure]: [MeasurementTypes_1.ObservationCode.SYSTOLIC_BLOOD_PRESSURE, MeasurementTypes_1.ObservationCode.DIASTOLIC_BLOOD_PRESSURE, MeasurementTypes_1.ObservationCode.MEAN_BLOOD_PRESSURE, MeasurementTypes_1.ObservationCode.BLOOD_PRESSURE_HEART_RATE, MeasurementTypes_1.PulseRhythmCoding.observation],
382
- [MeasurementTypes_1.MeasurementTypeKey.bloodOxygenPulseRate]: [MeasurementTypes_1.ObservationCode.OXYGEN_SATURATION, MeasurementTypes_1.ObservationCode.OXYGEN_SATURATION_HEART_RATE],
416
+ [MeasurementTypes_1.MeasurementTypeKey.bloodPressure]: [
417
+ MeasurementTypes_1.ObservationCode.SYSTOLIC_BLOOD_PRESSURE,
418
+ MeasurementTypes_1.ObservationCode.DIASTOLIC_BLOOD_PRESSURE,
419
+ MeasurementTypes_1.ObservationCode.MEAN_BLOOD_PRESSURE,
420
+ MeasurementTypes_1.ObservationCode.BLOOD_PRESSURE_HEART_RATE,
421
+ MeasurementTypes_1.PulseRhythmCoding.observation,
422
+ (0, reading_group_1.readingGroupCode)(MeasurementTypes_1.MeasurementTypeKey.bloodPressure),
423
+ ],
424
+ [MeasurementTypes_1.MeasurementTypeKey.bloodOxygenPulseRate]: [
425
+ MeasurementTypes_1.ObservationCode.OXYGEN_SATURATION,
426
+ MeasurementTypes_1.ObservationCode.OXYGEN_SATURATION_HEART_RATE,
427
+ (0, reading_group_1.readingGroupCode)(MeasurementTypes_1.MeasurementTypeKey.bloodOxygenPulseRate),
428
+ ],
383
429
  [MeasurementTypes_1.MeasurementTypeKey.stepCount]: [MeasurementTypes_1.ObservationCode.STEPS],
384
- [MeasurementTypes_1.MeasurementTypeKey.ecg]: [MeasurementTypes_1.ObservationCode.ECG, MeasurementTypes_1.ObservationCode.ECG_HEART_RATE, MeasurementTypes_1.ObservationCode.HEART_RATE],
430
+ [MeasurementTypes_1.MeasurementTypeKey.ecg]: [
431
+ MeasurementTypes_1.ObservationCode.ECG,
432
+ MeasurementTypes_1.ObservationCode.ECG_HEART_RATE,
433
+ MeasurementTypes_1.ObservationCode.HEART_RATE,
434
+ (0, reading_group_1.readingGroupCode)(MeasurementTypes_1.MeasurementTypeKey.ecg),
435
+ ],
385
436
  [MeasurementTypes_1.MeasurementTypeKey.uricAcid]: [
386
437
  MeasurementTypes_1.ObservationCode.URIC_ACID,
387
438
  ...MeasurementTypes_1.URINE_ANALYTE_DEFINITIONS.map((analyte) => analyte.code),
439
+ (0, reading_group_1.readingGroupCode)(MeasurementTypes_1.MeasurementTypeKey.uricAcid),
388
440
  ],
389
441
  [MeasurementTypes_1.MeasurementTypeKey.urineAnalysis]: [
390
442
  MeasurementTypes_1.ObservationCode.URIC_ACID,
391
443
  ...MeasurementTypes_1.URINE_ANALYTE_DEFINITIONS.map((analyte) => analyte.code),
444
+ (0, reading_group_1.readingGroupCode)(MeasurementTypes_1.MeasurementTypeKey.urineAnalysis),
392
445
  ],
393
446
  [MeasurementTypes_1.MeasurementTypeKey.lipidPanel]: [
394
447
  MeasurementTypes_1.ObservationCode.LIPID_PANEL,
@@ -8,14 +8,12 @@ export declare const MAX_OBSERVATION_BUNDLE_BYTES = 900000;
8
8
  */
9
9
  export declare const MAX_CONDITIONAL_OBSERVATION_ENTRIES = 8;
10
10
  /**
11
- * Points every observation after the first at the first, as the first `hasMember` (where readers look). A link to its
12
- * own `id`, as ECG segments carry, is dropped: the server replaces that id on create.
11
+ * Points every observation after the first at the first, as the first `hasMember` (where readers look), and the
12
+ * reading's group, which comes last, at every other observation. A link to its own `id`, as ECG segments carry, is
13
+ * dropped: the server replaces that id on create.
13
14
  */
14
15
  export declare const linkObservationMembers: (observations: Observation[]) => Observation[];
16
+ export declare const createdObservationReference: (response: Bundle, index: number) => string | undefined;
17
+ export declare const rewriteObservationReferences: (entries: BundleEntry[], from: string, to: string) => BundleEntry[];
15
18
  export declare const splitObservationBundleEntries: (bundle: Bundle) => BundleEntry[][] | undefined;
16
19
  export declare const executeObservationBundle: (bundle: Bundle, executeBatch: (bundle: Bundle) => Promise<Bundle>) => Promise<Bundle>;
17
- /**
18
- * Readings' entries packed into as few requests as fit `MAX_OBSERVATION_BUNDLE_BYTES`, each reading whole. A reading
19
- * too big for one request is a request by itself, which `executeObservationBundle` splits.
20
- */
21
- export declare const packObservationGroups: (groups: BundleEntry[][]) => BundleEntry[][][];
@@ -1,7 +1,9 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.packObservationGroups = exports.executeObservationBundle = exports.splitObservationBundleEntries = exports.linkObservationMembers = exports.MAX_CONDITIONAL_OBSERVATION_ENTRIES = exports.MAX_OBSERVATION_BUNDLE_BYTES = void 0;
3
+ exports.executeObservationBundle = exports.splitObservationBundleEntries = exports.rewriteObservationReferences = exports.createdObservationReference = exports.linkObservationMembers = exports.MAX_CONDITIONAL_OBSERVATION_ENTRIES = exports.MAX_OBSERVATION_BUNDLE_BYTES = void 0;
4
4
  const offline_1 = require("../offline");
5
+ const bundle_entry_status_1 = require("./bundle-entry-status");
6
+ const reading_group_1 = require("./reading-group");
5
7
  /**
6
8
  * Maximum serialized size, in bytes, of one observation bundle request.
7
9
  */
@@ -11,10 +13,18 @@ exports.MAX_OBSERVATION_BUNDLE_BYTES = 900000;
11
13
  */
12
14
  exports.MAX_CONDITIONAL_OBSERVATION_ENTRIES = 8;
13
15
  /**
14
- * Points every observation after the first at the first, as the first `hasMember` (where readers look). A link to its
15
- * own `id`, as ECG segments carry, is dropped: the server replaces that id on create.
16
+ * Points every observation after the first at the first, as the first `hasMember` (where readers look), and the
17
+ * reading's group, which comes last, at every other observation. A link to its own `id`, as ECG segments carry, is
18
+ * dropped: the server replaces that id on create.
16
19
  */
17
20
  const linkObservationMembers = (observations) => {
21
+ const parts = linkedToFirst(observations.filter((observation) => !(0, reading_group_1.isReadingGroup)(observation)));
22
+ const groups = observations.filter(reading_group_1.isReadingGroup);
23
+ const partReferences = parts.map((part) => ({ reference: `urn:uuid:${(0, offline_1.stableMeasurementId)(part)}` }));
24
+ return [...parts, ...groups.map((group) => ({ ...group, hasMember: partReferences }))];
25
+ };
26
+ exports.linkObservationMembers = linkObservationMembers;
27
+ const linkedToFirst = (observations) => {
18
28
  const main = observations[0];
19
29
  if (!main) {
20
30
  return observations;
@@ -34,7 +44,6 @@ const linkObservationMembers = (observations) => {
34
44
  };
35
45
  });
36
46
  };
37
- exports.linkObservationMembers = linkObservationMembers;
38
47
  const createdObservationReference = (response, index) => {
39
48
  var _a, _b, _c, _d;
40
49
  const entry = (_a = response.entry) === null || _a === void 0 ? void 0 : _a[index];
@@ -48,21 +57,31 @@ const createdObservationReference = (response, index) => {
48
57
  const match = location === null || location === void 0 ? void 0 : location.match(/(?:^|\/)(Observation\/[^/]+)(?:\/_history\/[^/]+)?$/);
49
58
  return match === null || match === void 0 ? void 0 : match[1];
50
59
  };
51
- const rewriteObservationReference = (entry, from, to) => {
52
- var _a;
53
- const resource = entry.resource;
54
- if ((resource === null || resource === void 0 ? void 0 : resource.resourceType) !== "Observation" || !((_a = resource.hasMember) === null || _a === void 0 ? void 0 : _a.length)) {
55
- return entry;
56
- }
57
- return {
58
- ...entry,
59
- resource: {
60
- ...resource,
61
- hasMember: resource.hasMember.map((reference) => reference.reference === from ? { ...reference, reference: to } : reference),
62
- },
63
- };
64
- };
65
- const rewriteObservationReferences = (entries, from, to) => entries.map((entry) => rewriteObservationReference(entry, from, to));
60
+ exports.createdObservationReference = createdObservationReference;
61
+ /** The placeholder other entries of a save use to point at `entry` before the server gives it an id. */
62
+ const placeholderOf = (entry) => { var _a, _b; return (_a = entry.fullUrl) !== null && _a !== void 0 ? _a : (((_b = entry.resource) === null || _b === void 0 ? void 0 : _b.resourceType) === "Observation" ? `urn:uuid:${(0, offline_1.stableMeasurementId)(entry.resource)}` : undefined); };
63
+ /** Points `hasMember` links at the saved observations in `saved`, by placeholder, where an earlier request saved them. */
64
+ const rewriteSavedReferences = (entries, saved) => saved.size === 0
65
+ ? entries
66
+ : entries.map((entry) => {
67
+ var _a;
68
+ const resource = entry.resource;
69
+ if ((resource === null || resource === void 0 ? void 0 : resource.resourceType) !== "Observation" || !((_a = resource.hasMember) === null || _a === void 0 ? void 0 : _a.length)) {
70
+ return entry;
71
+ }
72
+ return {
73
+ ...entry,
74
+ resource: {
75
+ ...resource,
76
+ hasMember: resource.hasMember.map((member) => {
77
+ const reference = member.reference && saved.get(member.reference);
78
+ return reference ? { ...member, reference } : member;
79
+ }),
80
+ },
81
+ };
82
+ });
83
+ const rewriteObservationReferences = (entries, from, to) => rewriteSavedReferences(entries, new Map([[from, to]]));
84
+ exports.rewriteObservationReferences = rewriteObservationReferences;
66
85
  const splitObservationBundleEntries = (bundle) => {
67
86
  var _a;
68
87
  const entries = (_a = bundle.entry) !== null && _a !== void 0 ? _a : [];
@@ -89,48 +108,44 @@ const splitObservationBundleEntries = (bundle) => {
89
108
  };
90
109
  exports.splitObservationBundleEntries = splitObservationBundleEntries;
91
110
  const executeObservationBundle = async (bundle, executeBatch) => {
92
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
111
+ var _a, _b, _c, _d, _e, _f;
93
112
  const entries = (_a = bundle.entry) !== null && _a !== void 0 ? _a : [];
94
113
  if (bundle.type === "transaction" &&
95
114
  entries.length > exports.MAX_CONDITIONAL_OBSERVATION_ENTRIES) {
96
- const rootReference = (_c = (_b = entries[0]) === null || _b === void 0 ? void 0 : _b.fullUrl) !== null && _c !== void 0 ? _c : (((_e = (_d = entries[0]) === null || _d === void 0 ? void 0 : _d.resource) === null || _e === void 0 ? void 0 : _e.resourceType) === "Observation"
97
- ? `urn:uuid:${(0, offline_1.stableMeasurementId)(entries[0].resource)}`
98
- : undefined);
115
+ const rootReference = entries[0] && placeholderOf(entries[0]);
99
116
  const transactionResponse = await (0, exports.executeObservationBundle)({ ...bundle, entry: entries.slice(0, 1) }, executeBatch);
100
117
  const savedRootReference = rootReference
101
- ? createdObservationReference(transactionResponse, 0)
118
+ ? (0, exports.createdObservationReference)(transactionResponse, 0)
102
119
  : undefined;
103
120
  const batchResponse = await (0, exports.executeObservationBundle)({
104
121
  ...bundle,
105
122
  type: "batch",
106
123
  entry: savedRootReference
107
- ? rewriteObservationReferences(entries.slice(1), rootReference, savedRootReference)
124
+ ? (0, exports.rewriteObservationReferences)(entries.slice(1), rootReference, savedRootReference)
108
125
  : entries.slice(1),
109
126
  }, executeBatch);
110
127
  return {
111
128
  resourceType: "Bundle",
112
129
  type: "batch-response",
113
130
  entry: [
114
- ...((_f = transactionResponse.entry) !== null && _f !== void 0 ? _f : []),
115
- ...((_g = batchResponse.entry) !== null && _g !== void 0 ? _g : []),
131
+ ...((_b = transactionResponse.entry) !== null && _b !== void 0 ? _b : []),
132
+ ...((_c = batchResponse.entry) !== null && _c !== void 0 ? _c : []),
116
133
  ],
117
134
  };
118
135
  }
119
136
  const chunks = (0, exports.splitObservationBundleEntries)(bundle);
120
137
  if (chunks) {
121
138
  const responses = [];
122
- const rootReference = (_j = (_h = entries[0]) === null || _h === void 0 ? void 0 : _h.fullUrl) !== null && _j !== void 0 ? _j : (((_l = (_k = entries[0]) === null || _k === void 0 ? void 0 : _k.resource) === null || _l === void 0 ? void 0 : _l.resourceType) === "Observation"
123
- ? `urn:uuid:${(0, offline_1.stableMeasurementId)(entries[0].resource)}`
124
- : undefined);
125
- let savedRootReference;
126
- for (const [index, entry] of chunks.entries()) {
127
- const chunkEntries = index > 0 && rootReference && savedRootReference
128
- ? rewriteObservationReferences(entry, rootReference, savedRootReference)
129
- : entry;
130
- const response = await (0, exports.executeObservationBundle)({ ...bundle, entry: chunkEntries }, executeBatch);
131
- if (index === 0 && rootReference) {
132
- savedRootReference = createdObservationReference(response, 0);
133
- }
139
+ const saved = new Map();
140
+ for (const chunk of chunks) {
141
+ const response = await (0, exports.executeObservationBundle)({ ...bundle, entry: rewriteSavedReferences(chunk, saved) }, executeBatch);
142
+ chunk.forEach((entry, index) => {
143
+ const placeholder = placeholderOf(entry);
144
+ const reference = (0, exports.createdObservationReference)(response, index);
145
+ if (placeholder && reference) {
146
+ saved.set(placeholder, reference);
147
+ }
148
+ });
134
149
  responses.push(response);
135
150
  }
136
151
  return {
@@ -140,40 +155,9 @@ const executeObservationBundle = async (bundle, executeBatch) => {
140
155
  };
141
156
  }
142
157
  const response = await executeBatch(bundle);
143
- if (((_o = (_m = response.entry) === null || _m === void 0 ? void 0 : _m.length) !== null && _o !== void 0 ? _o : 0) !== entries.length ||
144
- ((_p = response.entry) === null || _p === void 0 ? void 0 : _p.some((entry) => {
145
- var _a, _b;
146
- const status = (_b = (_a = entry.response) === null || _a === void 0 ? void 0 : _a.status) !== null && _b !== void 0 ? _b : "";
147
- return status.startsWith("4") || status.startsWith("5");
148
- }))) {
158
+ if (((_e = (_d = response.entry) === null || _d === void 0 ? void 0 : _d.length) !== null && _e !== void 0 ? _e : 0) !== entries.length || ((_f = response.entry) === null || _f === void 0 ? void 0 : _f.some(bundle_entry_status_1.isFailedEntry))) {
149
159
  throw response;
150
160
  }
151
161
  return response;
152
162
  };
153
163
  exports.executeObservationBundle = executeObservationBundle;
154
- /**
155
- * Readings' entries packed into as few requests as fit `MAX_OBSERVATION_BUNDLE_BYTES`, each reading whole. A reading
156
- * too big for one request is a request by itself, which `executeObservationBundle` splits.
157
- */
158
- const packObservationGroups = (groups) => {
159
- const envelope = JSON.stringify({ resourceType: "Bundle", type: "batch", entry: [] }).length;
160
- const requests = [];
161
- let request = [];
162
- let size = envelope;
163
- for (const group of groups) {
164
- // Each entry adds its JSON and a separating comma.
165
- const groupSize = group.reduce((total, entry) => total + JSON.stringify(entry).length + 1, 0);
166
- if (request.length > 0 && size + groupSize > exports.MAX_OBSERVATION_BUNDLE_BYTES) {
167
- requests.push(request);
168
- request = [];
169
- size = envelope;
170
- }
171
- request.push(group);
172
- size += groupSize;
173
- }
174
- if (request.length > 0) {
175
- requests.push(request);
176
- }
177
- return requests;
178
- };
179
- exports.packObservationGroups = packObservationGroups;
@@ -0,0 +1,12 @@
1
+ import { CodeableConcept, Observation, Quantity } from "@medplum/fhirtypes";
2
+ import { MeasurementTypeKey } from "./types/MeasurementTypeKey";
3
+ /** A quantity in `unit`, coded in UCUM when the unit has a UCUM code. */
4
+ export declare const ucumQuantity: (value: number, unit: string) => Quantity;
5
+ /** The FHIR observation category of a measurement type; vital signs unless it is a test, procedure or activity. */
6
+ export declare const observationCategory: (type: MeasurementTypeKey) => CodeableConcept[] | undefined;
7
+ /** The status and category every saved reading carries: a device result is final. */
8
+ export declare const readingStatusAndCategory: (type: MeasurementTypeKey) => Pick<Observation, "status" | "category">;
9
+ /** Marks a reading's first observation with the device user (the monitor's memory slot) who took it. */
10
+ export declare const withDeviceUser: (observations: Observation[], memorySlot: unknown) => Observation[];
11
+ /** The device user a reading was saved with, from whichever of its observations carries it. */
12
+ export declare const deviceUserOf: (observations: readonly Observation[]) => number | undefined;
@@ -0,0 +1,69 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.deviceUserOf = exports.withDeviceUser = exports.readingStatusAndCategory = exports.observationCategory = exports.ucumQuantity = void 0;
4
+ const fhir_systems_1 = require("./fhir-systems");
5
+ const MeasurementTypeKey_1 = require("./types/MeasurementTypeKey");
6
+ const UCUM_CODES = {
7
+ "%": "%",
8
+ "°C": "Cel",
9
+ bpm: "/min",
10
+ "breaths/min": "/min",
11
+ kg: "kg",
12
+ "mg/dL": "mg/dL",
13
+ "mL/kg/min": "mL/kg/min",
14
+ mmHg: "mm[Hg]",
15
+ ms: "ms",
16
+ mV: "mV",
17
+ s: "s",
18
+ steps: "{steps}",
19
+ };
20
+ /** A quantity in `unit`, coded in UCUM when the unit has a UCUM code. */
21
+ const ucumQuantity = (value, unit) => {
22
+ const code = UCUM_CODES[unit];
23
+ return code ? { value, unit, system: fhir_systems_1.UCUM_SYSTEM, code } : { value, unit };
24
+ };
25
+ exports.ucumQuantity = ucumQuantity;
26
+ const CATEGORY_BY_TYPE = {
27
+ [MeasurementTypeKey_1.MeasurementTypeKey.bloodGlucose]: "laboratory",
28
+ [MeasurementTypeKey_1.MeasurementTypeKey.urineAnalysis]: "laboratory",
29
+ [MeasurementTypeKey_1.MeasurementTypeKey.uricAcid]: "laboratory",
30
+ [MeasurementTypeKey_1.MeasurementTypeKey.lipidPanel]: "laboratory",
31
+ [MeasurementTypeKey_1.MeasurementTypeKey.ecg]: "procedure",
32
+ [MeasurementTypeKey_1.MeasurementTypeKey.spirometryPanel]: "procedure",
33
+ [MeasurementTypeKey_1.MeasurementTypeKey.stepCount]: "activity",
34
+ [MeasurementTypeKey_1.MeasurementTypeKey.babySleep]: "activity",
35
+ [MeasurementTypeKey_1.MeasurementTypeKey.symptomQuestionnaire]: "survey",
36
+ [MeasurementTypeKey_1.MeasurementTypeKey.respiratoryTherapy]: "therapy",
37
+ [MeasurementTypeKey_1.MeasurementTypeKey.photoUpload]: undefined,
38
+ };
39
+ /** The FHIR observation category of a measurement type; vital signs unless it is a test, procedure or activity. */
40
+ const observationCategory = (type) => {
41
+ const code = type in CATEGORY_BY_TYPE ? CATEGORY_BY_TYPE[type] : "vital-signs";
42
+ return code ? [{ coding: [{ system: fhir_systems_1.OBSERVATION_CATEGORY_SYSTEM, code }] }] : undefined;
43
+ };
44
+ exports.observationCategory = observationCategory;
45
+ const DEVICE_USER_URL = `${fhir_systems_1.OVOK_EXTENSION_BASE_URL}/device-user`;
46
+ /** The status and category every saved reading carries: a device result is final. */
47
+ const readingStatusAndCategory = (type) => {
48
+ const category = (0, exports.observationCategory)(type);
49
+ return { status: "final", ...(category ? { category } : {}) };
50
+ };
51
+ exports.readingStatusAndCategory = readingStatusAndCategory;
52
+ /** Marks a reading's first observation with the device user (the monitor's memory slot) who took it. */
53
+ const withDeviceUser = (observations, memorySlot) => typeof memorySlot === "number" && Number.isInteger(memorySlot)
54
+ ? observations.map((observation, index) => {
55
+ var _a;
56
+ return index === 0
57
+ ? { ...observation, extension: [...((_a = observation.extension) !== null && _a !== void 0 ? _a : []), { url: DEVICE_USER_URL, valueInteger: memorySlot }] }
58
+ : observation;
59
+ })
60
+ : observations;
61
+ exports.withDeviceUser = withDeviceUser;
62
+ /** The device user a reading was saved with, from whichever of its observations carries it. */
63
+ const deviceUserOf = (observations) => {
64
+ var _a;
65
+ return (_a = observations
66
+ .flatMap((observation) => { var _a; return (_a = observation.extension) !== null && _a !== void 0 ? _a : []; })
67
+ .find((extension) => extension.url === DEVICE_USER_URL)) === null || _a === void 0 ? void 0 : _a.valueInteger;
68
+ };
69
+ exports.deviceUserOf = deviceUserOf;
@@ -0,0 +1,12 @@
1
+ import { Bundle, BundleEntry } from "@medplum/fhirtypes";
2
+ /**
3
+ * Readings' entries packed into as few requests as fit `MAX_OBSERVATION_BUNDLE_BYTES`, each reading whole. A reading
4
+ * too big for one request is a request by itself, which `executeObservationBundle` splits.
5
+ */
6
+ export declare const packObservationGroups: (groups: BundleEntry[][]) => BundleEntry[][][];
7
+ /**
8
+ * Saves several readings as two batches, every main observation first, so a reading's other observations only ever
9
+ * point at a main observation the server saved. A main that matched several saved copies keeps the members saved
10
+ * with them.
11
+ */
12
+ export declare const executeReadingsBatch: (groups: BundleEntry[][], executeBatch: (bundle: Bundle) => Promise<Bundle>) => Promise<Bundle>;