@ovok/core 0.4.49-dev.519 → 0.4.49-dev.520

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 (37) 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 +5 -0
  4. package/dist/client/observation/fhir-systems.js +6 -1
  5. package/dist/client/observation/methods/generateObservationBodiesByMeasurement.js +7 -65
  6. package/dist/client/observation/methods/observationsToMeasurements.js +33 -7
  7. package/dist/client/observation/observation-bundle-utils.d.ts +2 -5
  8. package/dist/client/observation/observation-bundle-utils.js +9 -37
  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/series.d.ts +1 -1
  14. package/dist/client/observation/series.js +4 -2
  15. package/dist/client/observation/services/base-observation-service.d.ts +1 -1
  16. package/dist/client/observation/services/base-observation-service.js +6 -12
  17. package/dist/client/observation/services/blood-pressure.d.ts +2 -0
  18. package/dist/client/observation/services/blood-pressure.js +9 -5
  19. package/dist/client/observation/services/ecg-observation-fragments.d.ts +4 -0
  20. package/dist/client/observation/services/ecg-observation-fragments.js +30 -37
  21. package/dist/client/observation/services/ecg.d.ts +3 -1
  22. package/dist/client/observation/services/ecg.js +19 -19
  23. package/dist/client/observation/services/uric-acid-service.js +2 -12
  24. package/dist/client/observation/services/urine-analyte-values.d.ts +4 -0
  25. package/dist/client/observation/services/urine-analyte-values.js +23 -0
  26. package/dist/client/observation/types/UrineAnalytes.d.ts +15 -0
  27. package/dist/client/observation/types/UrineAnalytes.js +17 -9
  28. package/dist/client/observation/utils/getDeviceObject.js +15 -32
  29. package/dist/client/offline/offline-measurement-queue.js +2 -8
  30. package/dist/client/ovok-client.d.ts +1 -0
  31. package/dist/client/ovok-client.js +11 -6
  32. package/dist/conformance/capability-requirements.js +1 -1
  33. package/dist/next/resources/measurements/measurements-resource.d.ts +11 -2
  34. package/dist/next/resources/measurements/measurements-resource.js +31 -6
  35. package/dist/next/resources/measurements/observation-builder.js +12 -6
  36. package/dist/next/resources/measurements/save-error.js +3 -4
  37. package/package.json +1 -1
@@ -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,9 @@
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
+ export declare const OBSERVATION_CATEGORY_SYSTEM = "http://terminology.hl7.org/CodeSystem/observation-category";
3
7
  /** Identifier system of the device-side reading id that makes a save idempotent. */
4
8
  export declare const DEVICE_READING_IDENTIFIER_SYSTEM = "https://api.ovok.com/fhir/StructureDefinition/device-reading-id";
9
+ export declare const OVOK_EXTENSION_BASE_URL = "http://ovok.com/fhir/StructureDefinition";
@@ -1,7 +1,12 @@
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.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
+ exports.OBSERVATION_CATEGORY_SYSTEM = "http://terminology.hl7.org/CodeSystem/observation-category";
6
10
  /** Identifier system of the device-side reading id that makes a save idempotent. */
7
11
  exports.DEVICE_READING_IDENTIFIER_SYSTEM = "https://api.ovok.com/fhir/StructureDefinition/device-reading-id";
12
+ 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,21 @@ 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 blood_pressure_1 = require("../services/blood-pressure");
7
9
  const single_value_services_1 = require("../services/single-value-services");
8
10
  const DEFAULT_OBSERVATION_TIME_TOLERANCE_MS = 1000;
9
11
  const codeOf = (observation) => {
10
12
  var _a, _b, _c, _d, _e, _f, _g;
11
13
  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
14
  };
15
+ const PRESENCE_VALUES = {
16
+ [MeasurementTypes_1.UrinePresenceCoding.positive]: 1,
17
+ [MeasurementTypes_1.UrinePresenceCoding.negative]: 0,
18
+ };
13
19
  const valueOf = (observation) => {
14
- var _a;
15
- const value = (_a = observation.valueQuantity) === null || _a === void 0 ? void 0 : _a.value;
20
+ var _a, _b, _c, _d, _e, _f;
21
+ 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
22
  return typeof value === "number" ? value : undefined;
17
23
  };
18
24
  const irregularHeartbeatOf = (observations) => {
@@ -30,6 +36,13 @@ const irregularHeartbeatOf = (observations) => {
30
36
  }
31
37
  return result === MeasurementTypes_1.PulseRhythmCoding.regular ? false : undefined;
32
38
  };
39
+ const bloodPressureStatusOf = (observations) => {
40
+ var _a;
41
+ const status = (_a = observations
42
+ .flatMap((observation) => { var _a; return (_a = observation.extension) !== null && _a !== void 0 ? _a : []; })
43
+ .find((extension) => extension.url === blood_pressure_1.BLOOD_PRESSURE_STATUS_URL)) === null || _a === void 0 ? void 0 : _a.valueString;
44
+ return status ? { status: status } : {};
45
+ };
33
46
  const recordedAtOf = (observation) => {
34
47
  var _a, _b;
35
48
  const value = (_a = observation.effectiveDateTime) !== null && _a !== void 0 ? _a : (_b = observation.effectivePeriod) === null || _b === void 0 ? void 0 : _b.start;
@@ -45,6 +58,13 @@ const groupKey = (observation) => {
45
58
  const recordingId = ((_b = observation.hasMember) === null || _b === void 0 ? void 0 : _b.length) ? id.replace(/-\d+$/, "") : id;
46
59
  return recordingId || ((_c = recordedAtOf(observation)) === null || _c === void 0 ? void 0 : _c.toISOString()) || "unknown";
47
60
  };
61
+ /** A recording id the SDK assigns before saving; older saves kept it in `hasMember`, where it matches nothing. */
62
+ const UNSAVED_RECORDING_ID = /^ecg-\d+-\d+$/;
63
+ /** The id of the first observation a later segment or the heart rate points at. */
64
+ const mainIdOf = (observation) => {
65
+ var _a;
66
+ 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);
67
+ };
48
68
  const ecgGroupKey = (observation, observations) => {
49
69
  const parent = observations.find((candidate) => candidate.id &&
50
70
  observation.id &&
@@ -53,6 +73,10 @@ const ecgGroupKey = (observation, observations) => {
53
73
  if (parent) {
54
74
  return groupKey(parent);
55
75
  }
76
+ const mainId = mainIdOf(observation);
77
+ if (mainId && !UNSAVED_RECORDING_ID.test(mainId)) {
78
+ return mainId;
79
+ }
56
80
  if (codeOf(observation) === MeasurementTypes_1.ObservationCode.ECG) {
57
81
  return groupKey(observation);
58
82
  }
@@ -269,13 +293,14 @@ const baseMeasurement = (measurementTypeKey, observation) => ({
269
293
  ...(recordedAtOf(observation) ? { recordedAt: recordedAtOf(observation) } : {}),
270
294
  });
271
295
  const inverseGroup = (type, observations) => {
272
- var _a, _b, _c, _d, _e, _f, _g;
296
+ var _a, _b, _c, _d, _e, _f, _g, _h;
273
297
  const first = [...observations].sort((left, right) => {
274
298
  var _a, _b, _c, _d;
275
299
  return ((_b = (_a = recordedAtOf(left)) === null || _a === void 0 ? void 0 : _a.getTime()) !== null && _b !== void 0 ? _b : Number.MAX_SAFE_INTEGER) -
276
300
  ((_d = (_c = recordedAtOf(right)) === null || _c === void 0 ? void 0 : _c.getTime()) !== null && _d !== void 0 ? _d : Number.MAX_SAFE_INTEGER);
277
301
  })[0];
278
- const measurement = baseMeasurement(type, first);
302
+ const deviceUser = (0, observation_coding_1.deviceUserOf)(observations);
303
+ const measurement = { ...baseMeasurement(type, first), ...(deviceUser === undefined ? {} : { memorySlot: deviceUser }) };
279
304
  const value = (code) => firstValue(observations, code);
280
305
  const single = single_value_services_1.singleValueFields.get(type);
281
306
  if (single) {
@@ -291,6 +316,7 @@ const inverseGroup = (type, observations) => {
291
316
  meanArterialPressure: value(MeasurementTypes_1.ObservationCode.MEAN_BLOOD_PRESSURE),
292
317
  heartRate: value(MeasurementTypes_1.ObservationCode.BLOOD_PRESSURE_HEART_RATE),
293
318
  irregularHeartbeat: irregularHeartbeatOf(observations),
319
+ ...bloodPressureStatusOf(observations),
294
320
  };
295
321
  case MeasurementTypes_1.MeasurementTypeKey.bloodOxygenPulseRate:
296
322
  return {
@@ -317,7 +343,7 @@ const inverseGroup = (type, observations) => {
317
343
  ? observation.valueSampledData.data.split(/\s+/).filter(Boolean).map(Number)
318
344
  : [];
319
345
  });
320
- const diagnosticResult = (_d = (_c = first.interpretation) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.text;
346
+ 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
347
  const duration = observations.reduce((total, observation) => {
322
348
  var _a, _b, _c, _d;
323
349
  return total +
@@ -327,7 +353,7 @@ const inverseGroup = (type, observations) => {
327
353
  ...measurement,
328
354
  measurementTypeKey: type,
329
355
  diagramPoints: points,
330
- heartRate: (_e = value(MeasurementTypes_1.ObservationCode.ECG_HEART_RATE)) !== null && _e !== void 0 ? _e : value(MeasurementTypes_1.ObservationCode.HEART_RATE),
356
+ heartRate: (_f = value(MeasurementTypes_1.ObservationCode.ECG_HEART_RATE)) !== null && _f !== void 0 ? _f : value(MeasurementTypes_1.ObservationCode.HEART_RATE),
331
357
  ...(diagnosticResult ? { diagnosticResult } : {}),
332
358
  ...(duration > 0 ? { duration } : {}),
333
359
  };
@@ -342,7 +368,7 @@ const inverseGroup = (type, observations) => {
342
368
  };
343
369
  for (const observation of observations) {
344
370
  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);
371
+ 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
372
  const value = valueOf(observation);
347
373
  const key = analyteByCode[analyteCode !== null && analyteCode !== void 0 ? analyteCode : ""];
348
374
  if (key && typeof value === "number") {
@@ -12,10 +12,7 @@ export declare const MAX_CONDITIONAL_OBSERVATION_ENTRIES = 8;
12
12
  * own `id`, as ECG segments carry, is dropped: the server replaces that id on create.
13
13
  */
14
14
  export declare const linkObservationMembers: (observations: Observation[]) => Observation[];
15
+ export declare const createdObservationReference: (response: Bundle, index: number) => string | undefined;
16
+ export declare const rewriteObservationReferences: (entries: BundleEntry[], from: string, to: string) => BundleEntry[];
15
17
  export declare const splitObservationBundleEntries: (bundle: Bundle) => BundleEntry[][] | undefined;
16
18
  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,8 @@
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");
5
6
  /**
6
7
  * Maximum serialized size, in bytes, of one observation bundle request.
7
8
  */
@@ -48,6 +49,7 @@ const createdObservationReference = (response, index) => {
48
49
  const match = location === null || location === void 0 ? void 0 : location.match(/(?:^|\/)(Observation\/[^/]+)(?:\/_history\/[^/]+)?$/);
49
50
  return match === null || match === void 0 ? void 0 : match[1];
50
51
  };
52
+ exports.createdObservationReference = createdObservationReference;
51
53
  const rewriteObservationReference = (entry, from, to) => {
52
54
  var _a;
53
55
  const resource = entry.resource;
@@ -63,6 +65,7 @@ const rewriteObservationReference = (entry, from, to) => {
63
65
  };
64
66
  };
65
67
  const rewriteObservationReferences = (entries, from, to) => entries.map((entry) => rewriteObservationReference(entry, from, to));
68
+ exports.rewriteObservationReferences = rewriteObservationReferences;
66
69
  const splitObservationBundleEntries = (bundle) => {
67
70
  var _a;
68
71
  const entries = (_a = bundle.entry) !== null && _a !== void 0 ? _a : [];
@@ -98,13 +101,13 @@ const executeObservationBundle = async (bundle, executeBatch) => {
98
101
  : undefined);
99
102
  const transactionResponse = await (0, exports.executeObservationBundle)({ ...bundle, entry: entries.slice(0, 1) }, executeBatch);
100
103
  const savedRootReference = rootReference
101
- ? createdObservationReference(transactionResponse, 0)
104
+ ? (0, exports.createdObservationReference)(transactionResponse, 0)
102
105
  : undefined;
103
106
  const batchResponse = await (0, exports.executeObservationBundle)({
104
107
  ...bundle,
105
108
  type: "batch",
106
109
  entry: savedRootReference
107
- ? rewriteObservationReferences(entries.slice(1), rootReference, savedRootReference)
110
+ ? (0, exports.rewriteObservationReferences)(entries.slice(1), rootReference, savedRootReference)
108
111
  : entries.slice(1),
109
112
  }, executeBatch);
110
113
  return {
@@ -125,11 +128,11 @@ const executeObservationBundle = async (bundle, executeBatch) => {
125
128
  let savedRootReference;
126
129
  for (const [index, entry] of chunks.entries()) {
127
130
  const chunkEntries = index > 0 && rootReference && savedRootReference
128
- ? rewriteObservationReferences(entry, rootReference, savedRootReference)
131
+ ? (0, exports.rewriteObservationReferences)(entry, rootReference, savedRootReference)
129
132
  : entry;
130
133
  const response = await (0, exports.executeObservationBundle)({ ...bundle, entry: chunkEntries }, executeBatch);
131
134
  if (index === 0 && rootReference) {
132
- savedRootReference = createdObservationReference(response, 0);
135
+ savedRootReference = (0, exports.createdObservationReference)(response, 0);
133
136
  }
134
137
  responses.push(response);
135
138
  }
@@ -140,40 +143,9 @@ const executeObservationBundle = async (bundle, executeBatch) => {
140
143
  };
141
144
  }
142
145
  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
- }))) {
146
+ if (((_o = (_m = response.entry) === null || _m === void 0 ? void 0 : _m.length) !== null && _o !== void 0 ? _o : 0) !== entries.length || ((_p = response.entry) === null || _p === void 0 ? void 0 : _p.some(bundle_entry_status_1.isFailedEntry))) {
149
147
  throw response;
150
148
  }
151
149
  return response;
152
150
  };
153
151
  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>;
@@ -0,0 +1,51 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.executeReadingsBatch = exports.packObservationGroups = void 0;
4
+ const observation_bundle_utils_1 = require("./observation-bundle-utils");
5
+ /**
6
+ * Readings' entries packed into as few requests as fit `MAX_OBSERVATION_BUNDLE_BYTES`, each reading whole. A reading
7
+ * too big for one request is a request by itself, which `executeObservationBundle` splits.
8
+ */
9
+ const packObservationGroups = (groups) => {
10
+ const envelope = JSON.stringify({ resourceType: "Bundle", type: "batch", entry: [] }).length;
11
+ const requests = [];
12
+ let request = [];
13
+ let size = envelope;
14
+ for (const group of groups) {
15
+ // Each entry adds its JSON and a separating comma.
16
+ const groupSize = group.reduce((total, entry) => total + JSON.stringify(entry).length + 1, 0);
17
+ if (request.length > 0 && size + groupSize > observation_bundle_utils_1.MAX_OBSERVATION_BUNDLE_BYTES) {
18
+ requests.push(request);
19
+ request = [];
20
+ size = envelope;
21
+ }
22
+ request.push(group);
23
+ size += groupSize;
24
+ }
25
+ if (request.length > 0) {
26
+ requests.push(request);
27
+ }
28
+ return requests;
29
+ };
30
+ exports.packObservationGroups = packObservationGroups;
31
+ /**
32
+ * Saves several readings as two batches, every main observation first, so a reading's other observations only ever
33
+ * point at a main observation the server saved. A main that matched several saved copies keeps the members saved
34
+ * with them.
35
+ */
36
+ const executeReadingsBatch = async (groups, executeBatch) => {
37
+ var _a, _b;
38
+ const mains = await (0, observation_bundle_utils_1.executeObservationBundle)({ resourceType: "Bundle", type: "batch", entry: groups.flatMap((group) => group.slice(0, 1)) }, executeBatch);
39
+ const members = groups.flatMap((group, index) => {
40
+ var _a;
41
+ const placeholder = (_a = group[0]) === null || _a === void 0 ? void 0 : _a.fullUrl;
42
+ const saved = (0, observation_bundle_utils_1.createdObservationReference)(mains, index);
43
+ return placeholder && saved ? (0, observation_bundle_utils_1.rewriteObservationReferences)(group.slice(1), placeholder, saved) : [];
44
+ });
45
+ if (members.length === 0) {
46
+ return mains;
47
+ }
48
+ const rest = await (0, observation_bundle_utils_1.executeObservationBundle)({ resourceType: "Bundle", type: "batch", entry: members }, executeBatch);
49
+ return { resourceType: "Bundle", type: "batch-response", entry: [...((_a = mains.entry) !== null && _a !== void 0 ? _a : []), ...((_b = rest.entry) !== null && _b !== void 0 ? _b : [])] };
50
+ };
51
+ exports.executeReadingsBatch = executeReadingsBatch;
@@ -11,7 +11,7 @@ export type SeriesObservationParams = {
11
11
  patientId: string;
12
12
  /** Device that recorded the series. */
13
13
  device?: MeasurementDevice;
14
- /** `preliminary` for values a device's own recording may still replace. */
14
+ /** Defaults to `final`; `preliminary` for values a device's own recording may still replace. */
15
15
  status?: Observation["status"];
16
16
  };
17
17
  /**
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.summarizeSeries = exports.readSeries = exports.seriesObservations = void 0;
4
+ const observation_coding_1 = require("./observation-coding");
4
5
  const creator_1 = require("./services/creator");
5
6
  const getDeviceObject_1 = require("./utils/getDeviceObject");
6
7
  /** FHIR's mark for a slot with no value. */
@@ -14,7 +15,7 @@ const sampledData = (values, decimals) => values
14
15
  * single reading of that kind. Save them with `saveObservations`, which links the rest to the first. ECG recordings
15
16
  * keep their own path, `generateObservationBodiesByMeasurement`.
16
17
  */
17
- const seriesObservations = ({ series, patientId, device, status = "registered", }) => {
18
+ const seriesObservations = ({ series, patientId, device, status = "final", }) => {
18
19
  const service = creator_1.ObservationServiceCreator.getInstance().getService(series.measurementTypeKey);
19
20
  const codes = service.getObservationCodes();
20
21
  const slots = Math.max(0, ...Object.values(series.values).map((values) => { var _a; return (_a = values === null || values === void 0 ? void 0 : values.length) !== null && _a !== void 0 ? _a : 0; }));
@@ -30,13 +31,14 @@ const seriesObservations = ({ series, patientId, device, status = "registered",
30
31
  }
31
32
  return [{
32
33
  resourceType: "Observation",
34
+ ...(0, observation_coding_1.readingStatusAndCategory)(series.measurementTypeKey),
33
35
  status,
34
36
  subject: { reference: `Patient/${patientId}` },
35
37
  device: (0, getDeviceObject_1.getDeviceObject)(device),
36
38
  code,
37
39
  effectivePeriod,
38
40
  valueSampledData: {
39
- origin: { value: 0, unit: field.unit },
41
+ origin: (0, observation_coding_1.ucumQuantity)(0, field.unit),
40
42
  period: series.periodMs,
41
43
  dimensions: 1,
42
44
  data: sampledData(values, field.decimals),
@@ -17,7 +17,7 @@ export declare abstract class BaseObservationService<T extends Measurement> impl
17
17
  protected getCastedMeasurement(measurement: Measurement): T;
18
18
  generateValues(measurement: Measurement): ObservationValue[];
19
19
  getObservationCodes(): CodeableConcept[];
20
- getAdditionalProperties(_measurement: Measurement): Partial<Observation>[];
20
+ getAdditionalProperties(measurement: Measurement): Partial<Observation>[];
21
21
  getUnits(): string[];
22
22
  getMeasurementDisplay(measurement: Measurement): string;
23
23
  getObservationDisplay(observations: Observation[]): string | undefined;
@@ -2,6 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.BaseObservationService = void 0;
4
4
  const fhir_systems_1 = require("../fhir-systems");
5
+ const observation_coding_1 = require("../observation-coding");
6
+ const measurement_time_1 = require("./measurement-time");
5
7
  class BaseObservationService {
6
8
  getFields() {
7
9
  return this.observationMetadata.map(({ valueKey, primaryCode, unit, toFixed, display }) => ({
@@ -30,14 +32,7 @@ class BaseObservationService {
30
32
  throw new Error(`${metadata.valueKey} must be a number but got ${value}`);
31
33
  }
32
34
  const fixedValue = numberValue.toFixed(metadata.toFixed);
33
- return {
34
- valueQuantity: {
35
- value: Number(fixedValue),
36
- unit: metadata.unit,
37
- code: metadata.primaryCode,
38
- system: fhir_systems_1.LOINC_SYSTEM,
39
- },
40
- };
35
+ return { valueQuantity: (0, observation_coding_1.ucumQuantity)(Number(fixedValue), metadata.unit) };
41
36
  });
42
37
  }
43
38
  getObservationCodes() {
@@ -57,10 +52,9 @@ class BaseObservationService {
57
52
  text: metadata.display,
58
53
  }));
59
54
  }
60
- getAdditionalProperties(_measurement) {
61
- return Object.values(this.observationMetadata).map(() => ({
62
- effectiveDateTime: new Date().toISOString(),
63
- }));
55
+ getAdditionalProperties(measurement) {
56
+ const effectiveDateTime = (0, measurement_time_1.recordedAtOrNow)(measurement).toISOString();
57
+ return this.observationMetadata.map(() => ({ effectiveDateTime }));
64
58
  }
65
59
  getUnits() {
66
60
  return this.observationMetadata.map((metadata) => metadata.unit);
@@ -5,6 +5,8 @@ import { Sample } from "../types/generate-measurement/Sample";
5
5
  import { ObservationValue } from "../types/generate-observation-body/ObservationValue";
6
6
  import { ObservationMetadata } from "../types/service/ObservationMetadata";
7
7
  import { BaseObservationService } from "./base-observation-service";
8
+ /** The monitor's measurement status (movement, loose cuff), kept on the systolic observation. */
9
+ export declare const BLOOD_PRESSURE_STATUS_URL = "http://ovok.com/fhir/StructureDefinition/blood-pressure-measurement-status";
8
10
  export declare class BloodPressureService extends BaseObservationService<BloodPressureMeasurement> {
9
11
  protected measurementTypeKey: MeasurementTypeKey;
10
12
  protected measurementTypeName: string;