@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
@@ -3,8 +3,10 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.EcgService = void 0;
4
4
  const MeasurementTypes_1 = require("../../../types/MeasurementTypes");
5
5
  const fhir_systems_1 = require("../fhir-systems");
6
+ const observation_coding_1 = require("../observation-coding");
6
7
  const base_observation_service_1 = require("./base-observation-service");
7
8
  const ecg_observation_fragments_1 = require("./ecg-observation-fragments");
9
+ const measurement_time_1 = require("./measurement-time");
8
10
  class EcgService extends base_observation_service_1.BaseObservationService {
9
11
  constructor() {
10
12
  super(...arguments);
@@ -35,29 +37,18 @@ class EcgService extends base_observation_service_1.BaseObservationService {
35
37
  const heartRate = castedMeasurement.heartRate;
36
38
  const diagramPoints = castedMeasurement.diagramPoints;
37
39
  if (diagramPoints === null || diagramPoints === void 0 ? void 0 : diagramPoints.length) {
38
- const duration = castedMeasurement.duration;
39
- const period = typeof duration === "number" && Number.isFinite(duration) && duration > 0
40
- ? (duration * 1000) / diagramPoints.length
41
- : 1;
42
40
  values.push({
43
41
  valueSampledData: {
44
- origin: { value: 0, unit: "mV" },
45
- period,
42
+ origin: { value: 0, unit: "mV", system: fhir_systems_1.UCUM_SYSTEM, code: "mV" },
43
+ period: (0, ecg_observation_fragments_1.ecgSamplePeriodMs)(castedMeasurement),
46
44
  dimensions: 1,
47
- data: diagramPoints.join(" "),
45
+ data: (0, ecg_observation_fragments_1.sampledDataOf)(diagramPoints),
48
46
  },
49
47
  });
50
48
  }
51
49
  if (typeof heartRate === "number") {
52
50
  const fixedValue = heartRate.toFixed(this.observationMetadata[1].toFixed);
53
- values.push({
54
- valueQuantity: {
55
- value: Number(fixedValue),
56
- unit: "bpm",
57
- code: MeasurementTypes_1.ObservationCode.ECG_HEART_RATE,
58
- system: fhir_systems_1.LOINC_SYSTEM,
59
- },
60
- });
51
+ values.push({ valueQuantity: (0, observation_coding_1.ucumQuantity)(Number(fixedValue), "bpm") });
61
52
  }
62
53
  return values;
63
54
  }
@@ -68,9 +59,10 @@ class EcgService extends base_observation_service_1.BaseObservationService {
68
59
  }
69
60
  getAdditionalProperties(measurement) {
70
61
  const castedMeasurement = this.getCastedMeasurement(measurement);
62
+ const effectiveDateTime = (0, measurement_time_1.recordedAtOrNow)(castedMeasurement).toISOString();
71
63
  const additionalProperties = [
72
64
  {
73
- effectiveDateTime: new Date().toISOString(),
65
+ effectiveDateTime,
74
66
  interpretation: [
75
67
  {
76
68
  text: castedMeasurement.diagnosticResult,
@@ -96,12 +88,20 @@ class EcgService extends base_observation_service_1.BaseObservationService {
96
88
  },
97
89
  ],
98
90
  },
99
- {
100
- effectiveDateTime: new Date().toISOString(),
101
- },
91
+ { effectiveDateTime },
102
92
  ];
103
93
  return additionalProperties;
104
94
  }
95
+ /** The waveform is coded in the ISO/IEEE 11073 nomenclature, not LOINC. */
96
+ getObservationCodes() {
97
+ return super.getObservationCodes().map((concept) => {
98
+ var _a;
99
+ return ({
100
+ ...concept,
101
+ coding: (_a = concept.coding) === null || _a === void 0 ? void 0 : _a.map((coding) => coding.code === MeasurementTypes_1.ObservationCode.ECG ? { ...coding, system: fhir_systems_1.MDC_SYSTEM } : coding),
102
+ });
103
+ });
104
+ }
105
105
  getMeasurementDisplay(measurement) {
106
106
  const castedMeasurement = this.getCastedMeasurement(measurement);
107
107
  return castedMeasurement.diagnosticResult || "Unknown";
@@ -5,6 +5,7 @@ const MeasurementTypes_1 = require("../../../types/MeasurementTypes");
5
5
  const fhir_systems_1 = require("../fhir-systems");
6
6
  const base_observation_service_1 = require("./base-observation-service");
7
7
  const measurement_time_1 = require("./measurement-time");
8
+ const urine_analyte_values_1 = require("./urine-analyte-values");
8
9
  class UricAcidService extends base_observation_service_1.BaseObservationService {
9
10
  constructor() {
10
11
  super(...arguments);
@@ -82,18 +83,7 @@ class UricAcidService extends base_observation_service_1.BaseObservationService
82
83
  ],
83
84
  text: analyte.display,
84
85
  },
85
- value: {
86
- valueQuantity: {
87
- value,
88
- ...(analyte.unit ? { unit: analyte.unit } : {}),
89
- ...(analyte.unitCode
90
- ? {
91
- code: analyte.unitCode,
92
- system: fhir_systems_1.UCUM_SYSTEM,
93
- }
94
- : {}),
95
- },
96
- },
86
+ value: (0, urine_analyte_values_1.analyteValue)(analyte, value),
97
87
  additionalProperties: {
98
88
  effectiveDateTime,
99
89
  },
@@ -0,0 +1,4 @@
1
+ import { UrineAnalyteDefinition } from "../../../types/MeasurementTypes";
2
+ import { ObservationValue } from "../types/generate-observation-body/ObservationValue";
3
+ /** A strip analyte's value: coded positive or negative for a presence test, else a quantity. */
4
+ export declare const analyteValue: (analyte: UrineAnalyteDefinition, value: number) => ObservationValue;
@@ -0,0 +1,27 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.analyteValue = void 0;
4
+ const MeasurementTypes_1 = require("../../../types/MeasurementTypes");
5
+ const fhir_systems_1 = require("../fhir-systems");
6
+ const presenceValue = (value) => {
7
+ const positive = value > 0;
8
+ return {
9
+ valueCodeableConcept: {
10
+ coding: [{
11
+ system: MeasurementTypes_1.UrinePresenceCoding.system,
12
+ code: positive ? MeasurementTypes_1.UrinePresenceCoding.positive : MeasurementTypes_1.UrinePresenceCoding.negative,
13
+ display: positive ? "Positive" : "Negative",
14
+ }],
15
+ },
16
+ };
17
+ };
18
+ const analyteQuantity = (analyte, value) => ({
19
+ valueQuantity: {
20
+ value,
21
+ ...(analyte.unit ? { unit: analyte.unit } : {}),
22
+ ...(analyte.unitCode ? { code: analyte.unitCode, system: fhir_systems_1.UCUM_SYSTEM } : {}),
23
+ },
24
+ });
25
+ /** A strip analyte's value: coded positive or negative for a presence test, else a quantity. */
26
+ const analyteValue = (analyte, value) => analyte.presence ? presenceValue(value) : analyteQuantity(analyte, value);
27
+ exports.analyteValue = analyteValue;
@@ -20,6 +20,21 @@ export type UrineAnalyteDefinition = {
20
20
  unit?: string;
21
21
  /** UCUM code sent in Observation.valueQuantity.code. */
22
22
  unitCode?: string;
23
+ /** A presence test, saved as a positive or negative coded value instead of a quantity. */
24
+ presence?: boolean;
25
+ };
26
+ /**
27
+ * SNOMED CT results of a urine presence test such as nitrite.
28
+ *
29
+ * @category measurements
30
+ */
31
+ export declare const UrinePresenceCoding: {
32
+ /** Coding system URI (SNOMED CT). */
33
+ readonly system: "http://snomed.info/sct";
34
+ /** Positive. */
35
+ readonly positive: "10828004";
36
+ /** Negative. */
37
+ readonly negative: "260385009";
23
38
  };
24
39
  /**
25
40
  * LOINC mappings for the analytes returned by Contec's BC401 strips.
@@ -1,6 +1,19 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.URINE_ANALYTE_DEFINITIONS = void 0;
3
+ exports.URINE_ANALYTE_DEFINITIONS = exports.UrinePresenceCoding = void 0;
4
+ /**
5
+ * SNOMED CT results of a urine presence test such as nitrite.
6
+ *
7
+ * @category measurements
8
+ */
9
+ exports.UrinePresenceCoding = {
10
+ /** Coding system URI (SNOMED CT). */
11
+ system: "http://snomed.info/sct",
12
+ /** Positive. */
13
+ positive: "10828004",
14
+ /** Negative. */
15
+ negative: "260385009",
16
+ };
4
17
  /**
5
18
  * LOINC mappings for the analytes returned by Contec's BC401 strips.
6
19
  * These are exported so Native declarations and consuming apps can describe
@@ -50,13 +63,8 @@ exports.URINE_ANALYTE_DEFINITIONS = [
50
63
  unit: "mg/dL",
51
64
  unitCode: "mg/dL",
52
65
  },
53
- { key: "ph", code: "50560-2", display: "Urine pH" },
54
- {
55
- key: "nit",
56
- code: "50558-6",
57
- display: "Nitrite",
58
- unit: "qualitative",
59
- },
66
+ { key: "ph", code: "50560-2", display: "Urine pH", unit: "[pH]", unitCode: "[pH]" },
67
+ { key: "nit", code: "50558-6", display: "Nitrite", presence: true },
60
68
  {
61
69
  key: "leu",
62
70
  code: "60026-2",
@@ -64,7 +72,7 @@ exports.URINE_ANALYTE_DEFINITIONS = [
64
72
  unit: "WBC/µL",
65
73
  unitCode: "/uL",
66
74
  },
67
- { key: "sg", code: "53326-5", display: "Specific gravity" },
75
+ { key: "sg", code: "53326-5", display: "Specific gravity", unitCode: "1" },
68
76
  {
69
77
  key: "vc",
70
78
  code: "5768-7",
@@ -3,7 +3,6 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.getDeviceObject = void 0;
4
4
  const EXTENSION_BASE_URL = "http://ovok.com/fhir/StructureDefinition";
5
5
  const LOCAL_NAME_URL = `${EXTENSION_BASE_URL}/device-local-name`;
6
- const MANUFACTURER_DATA_URL = `${EXTENSION_BASE_URL}/device-manufacturer-data`;
7
6
  const MANUFACTURER_NAME_URL = `${EXTENSION_BASE_URL}/device-manufacturer-name`;
8
7
  const MODEL_URL = `${EXTENSION_BASE_URL}/device-model`;
9
8
  const SERIAL_NUMBER_URL = `${EXTENSION_BASE_URL}/device-serial-number`;
@@ -39,7 +38,7 @@ const getOptionalStringExtension = (url, value) => {
39
38
  return [{ url, valueString: value }];
40
39
  };
41
40
  const getDeviceObject = (measurementDevice) => {
42
- var _a, _b, _c, _d, _e;
41
+ var _a, _b, _c, _d;
43
42
  if (!measurementDevice) {
44
43
  return {
45
44
  identifier: {
@@ -47,37 +46,21 @@ const getDeviceObject = (measurementDevice) => {
47
46
  },
48
47
  };
49
48
  }
49
+ const display = measurementDevice.variant
50
+ ? variantDisplay(measurementDevice.variant)
51
+ : measurementDevice.name;
52
+ const extension = [
53
+ ...getOptionalStringExtension(LOCAL_NAME_URL, measurementDevice.localName),
54
+ ...getOptionalStringExtension(MANUFACTURER_NAME_URL, (_b = (_a = measurementDevice.variant) === null || _a === void 0 ? void 0 : _a.manufacturer) !== null && _b !== void 0 ? _b : measurementDevice.manufacturerName),
55
+ ...getOptionalStringExtension(MODEL_URL, (_d = (_c = measurementDevice.variant) === null || _c === void 0 ? void 0 : _c.model) !== null && _d !== void 0 ? _d : measurementDevice.model),
56
+ ...(measurementDevice.variant ? getOptionalStringExtension(PARSER_URL, measurementDevice.name) : []),
57
+ ...getOptionalStringExtension(SERIAL_NUMBER_URL, measurementDevice.sn),
58
+ ...getBatteryExtension(measurementDevice.batteryPercentage),
59
+ ];
50
60
  return {
51
- ...(measurementDevice.sn
52
- ? {
53
- identifier: {
54
- value: measurementDevice.sn,
55
- },
56
- }
57
- : {}),
58
- display: measurementDevice.variant
59
- ? variantDisplay(measurementDevice.variant)
60
- : (_a = measurementDevice.name) !== null && _a !== void 0 ? _a : "no-name",
61
- extension: [
62
- {
63
- url: LOCAL_NAME_URL,
64
- valueString: measurementDevice.localName || "no-local-name",
65
- },
66
- {
67
- url: MANUFACTURER_DATA_URL,
68
- valueString: measurementDevice.manufacturerData || "no-manufacturer-data",
69
- },
70
- ...getOptionalStringExtension(MANUFACTURER_NAME_URL, (_c = (_b = measurementDevice.variant) === null || _b === void 0 ? void 0 : _b.manufacturer) !== null && _c !== void 0 ? _c : measurementDevice.manufacturerName),
71
- ...getOptionalStringExtension(MODEL_URL, (_e = (_d = measurementDevice.variant) === null || _d === void 0 ? void 0 : _d.model) !== null && _e !== void 0 ? _e : measurementDevice.model),
72
- ...(measurementDevice.variant
73
- ? getOptionalStringExtension(PARSER_URL, measurementDevice.name)
74
- : []),
75
- {
76
- url: SERIAL_NUMBER_URL,
77
- valueString: measurementDevice.sn || "no-serial-number",
78
- },
79
- ...getBatteryExtension(measurementDevice.batteryPercentage),
80
- ],
61
+ ...(measurementDevice.sn ? { identifier: { value: measurementDevice.sn } } : {}),
62
+ ...(display ? { display } : {}),
63
+ ...(extension.length > 0 ? { extension } : {}),
81
64
  };
82
65
  };
83
66
  exports.getDeviceObject = getDeviceObject;
@@ -1,6 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.stableMeasurementId = exports.entryForObservation = exports.OFFLINE_MEASUREMENT_IDENTIFIER_SYSTEM = exports.DEFAULT_OFFLINE_MEASUREMENT_QUEUE_KEY = exports.OfflineMeasurementQueue = exports.OFFLINE_MEASUREMENT_QUEUE_STORAGE_KEY = void 0;
4
+ const bundle_entry_status_1 = require("../observation/bundle-entry-status");
4
5
  const fhir_systems_1 = require("../observation/fhir-systems");
5
6
  const request_options_1 = require("../request-options");
6
7
  /**
@@ -125,14 +126,7 @@ const entryForObservation = (observation, { identifierSystems = [], replace = fa
125
126
  };
126
127
  };
127
128
  exports.entryForObservation = entryForObservation;
128
- const isFailedResponse = (bundle) => {
129
- var _a, _b;
130
- return (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a.some((entry) => {
131
- var _a, _b;
132
- const status = (_b = (_a = entry.response) === null || _a === void 0 ? void 0 : _a.status) !== null && _b !== void 0 ? _b : "";
133
- return status.startsWith("4") || status.startsWith("5");
134
- })) !== null && _b !== void 0 ? _b : false;
135
- };
129
+ const isFailedResponse = (bundle) => { var _a, _b; return (_b = (_a = bundle.entry) === null || _a === void 0 ? void 0 : _a.some(bundle_entry_status_1.isFailedEntry)) !== null && _b !== void 0 ? _b : false; };
136
130
  /** The stored failure: name, and code/status when present; never the message or payload. */
137
131
  const summarizeFailure = (error) => {
138
132
  const failure = error;
@@ -159,6 +159,7 @@ export declare class OvokClient extends MedplumClient {
159
159
  * account differs from `account`: the rest of a reading is never written under someone else's sign-in.
160
160
  */
161
161
  private executeObservationBundle;
162
+ private executeSave;
162
163
  private mapError;
163
164
  private bindMethods;
164
165
  /**
@@ -57,6 +57,7 @@ const inviteMethods = __importStar(require("./invites/methods"));
57
57
  const notificationMethods = __importStar(require("./notifications/methods"));
58
58
  const observationMethods = __importStar(require("./observation/methods"));
59
59
  const observation_bundle_utils_1 = require("./observation/observation-bundle-utils");
60
+ const observation_groups_1 = require("./observation/observation-groups");
60
61
  const offline_1 = require("./offline");
61
62
  const patientMethods = __importStar(require("./patient/methods"));
62
63
  const patientSharingMethods = __importStar(require("./patient-sharing/methods"));
@@ -384,10 +385,11 @@ class OvokClient extends core_1.MedplumClient {
384
385
  .filter((group) => group.length > 0)
385
386
  .map((group) => (0, observation_bundle_utils_1.linkObservationMembers)(group).map((observation) => (0, offline_1.entryForObservation)(observation, entryOptions)));
386
387
  const responses = [];
387
- for (const request of (0, observation_bundle_utils_1.packObservationGroups)(entryGroups)) {
388
- // A reading alone keeps a single save's atomicity; several share a batch.
389
- const type = request.length === 1 ? "transaction" : "batch";
390
- responses.push(await this.executeObservationBundle({ resourceType: "Bundle", type, entry: request.flat() }, requestOptions, account));
388
+ for (const request of (0, observation_groups_1.packObservationGroups)(entryGroups)) {
389
+ // A reading alone keeps a single save's atomicity; several go main observations first.
390
+ responses.push(request.length === 1
391
+ ? await this.executeObservationBundle({ resourceType: "Bundle", type: "transaction", entry: request.flat() }, requestOptions, account)
392
+ : await this.executeSave((execute) => (0, observation_groups_1.executeReadingsBatch)(request, execute), requestOptions, account));
391
393
  }
392
394
  return {
393
395
  resourceType: "Bundle",
@@ -535,9 +537,12 @@ class OvokClient extends core_1.MedplumClient {
535
537
  * Sends a save's bundle, over several requests when it must. A later request isn't sent once the signed-in
536
538
  * account differs from `account`: the rest of a reading is never written under someone else's sign-in.
537
539
  */
538
- async executeObservationBundle(bundle, requestOptions, account = this.accountKey()) {
540
+ executeObservationBundle(bundle, requestOptions, account = this.accountKey()) {
541
+ return this.executeSave((execute) => (0, observation_bundle_utils_1.executeObservationBundle)(bundle, execute), requestOptions, account);
542
+ }
543
+ async executeSave(run, requestOptions, account = this.accountKey()) {
539
544
  try {
540
- const response = await (0, observation_bundle_utils_1.executeObservationBundle)(bundle, (request) => {
545
+ const response = await run((request) => {
541
546
  if (this.accountKey() !== account) {
542
547
  throw new Error("The signed-in account changed during the save; the rest of it was not sent.");
543
548
  }
@@ -26,7 +26,7 @@ exports.OVOK_CORE_REQUIREMENTS = {
26
26
  description: "The FHIR surface a server must provide for the @ovok/core client library's own methods to function.",
27
27
  software: {
28
28
  name: "@ovok/core",
29
- version: "0.4.49-rc.4",
29
+ version: "0.4.49-rc.5",
30
30
  },
31
31
  fhirVersion: "4.0.1",
32
32
  format: ["json"],
@@ -48,7 +48,8 @@ export declare const useObservations: <T extends readonly SupportedType[]>({ typ
48
48
  */
49
49
  export declare const useSaveMeasurement: () => ((params: GenerateObservationBodyParams, requestOptions?: MedplumRequestOptions) => Promise<Awaited<ReturnType<OvokClient["saveMeasurement"]>>>);
50
50
  /**
51
- * Loads an ECG Observation, plus its member Observations, and maps them to one recording; without `id`, loads all ECG Observations.
51
+ * Loads an ECG Observation, plus the Observations it points at or that point at it, and maps them to one recording;
52
+ * without `id`, loads all ECG Observations.
52
53
  *
53
54
  * @param id - Id of the ECG Observation.
54
55
  */
@@ -84,7 +84,8 @@ const useSaveMeasurement = () => {
84
84
  };
85
85
  exports.useSaveMeasurement = useSaveMeasurement;
86
86
  /**
87
- * Loads an ECG Observation, plus its member Observations, and maps them to one recording; without `id`, loads all ECG Observations.
87
+ * Loads an ECG Observation, plus the Observations it points at or that point at it, and maps them to one recording;
88
+ * without `id`, loads all ECG Observations.
88
89
  *
89
90
  * @param id - Id of the ECG Observation.
90
91
  */
@@ -98,10 +99,10 @@ const useEcgRecording = (id) => {
98
99
  return client.searchResources("Observation", query, { signal });
99
100
  }
100
101
  const [root, members] = await Promise.all([
101
- client.searchResources("Observation", { ...query, _id: id }, { signal }),
102
+ client.searchResources("Observation", { ...query, _id: id, _include: "Observation:has-member" }, { signal }),
102
103
  client.searchResources("Observation", { ...query, "has-member": `Observation/${id}` }, { signal }),
103
104
  ]);
104
- return [...root, ...members];
105
+ return [...new Map([...root, ...members].map((observation) => [observation.id, observation])).values()];
105
106
  }, id);
106
107
  const recording = (0, observationsToMeasurements_1.observationsToMeasurements)(observations, [types_1.MeasurementTypeKey.ecg])[0];
107
108
  return {
@@ -99,7 +99,11 @@ export declare class MeasurementsResource {
99
99
  save(params: BuildObservationsParams, options?: SaveObservationsOptions): Promise<SaveObservationsResult>;
100
100
  /** One reading, main observation first, created conditionally so a retry cannot duplicate it. */
101
101
  saveObservations(observations: Observation[], options?: SaveObservationsOptions): Promise<SaveObservationsResult>;
102
- /** Many readings, each main observation first, in as few requests as fit; a reading alone stays atomic. */
102
+ /**
103
+ * Many readings, each main observation first, in as few requests as fit. A request holding one reading is a
104
+ * transaction, atomic when the project enables FHIR transactions. A request holding several is two batches, main
105
+ * observations first: if it fails, some readings may be saved and others not, and saving them again is safe.
106
+ */
103
107
  saveObservationGroups(groups: Observation[][], options?: SaveObservationsOptions): Promise<Bundle>;
104
108
  /** Builds the Observations for a measurement without saving them. */
105
109
  build(params: BuildObservationsParams): Promise<Observation[]>;
@@ -112,8 +116,13 @@ export declare class MeasurementsResource {
112
116
  /** The comma-joined codes the types are saved under, as `latest` and FHIR `code` searches take them. */
113
117
  codesFor(types: MeasurementCodeTypes): string;
114
118
  private latestPatientId;
115
- /** A reading split over several requests stops once another account signs in, so none of it lands elsewhere. */
119
+ /**
120
+ * A reading split over several requests stops once another account signs in, so none of it lands elsewhere. A
121
+ * transaction refused because its main observation matched several saved copies is sent again as batches.
122
+ */
116
123
  private send;
124
+ private sendReadings;
125
+ private guarded;
117
126
  private currentOwnerKey;
118
127
  private requireOwner;
119
128
  }
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MeasurementsResource = void 0;
4
4
  const observationsToMeasurements_1 = require("../../../client/observation/methods/observationsToMeasurements");
5
5
  const observation_bundle_utils_1 = require("../../../client/observation/observation-bundle-utils");
6
+ const observation_groups_1 = require("../../../client/observation/observation-groups");
6
7
  const offline_measurement_queue_1 = require("../../../client/offline/offline-measurement-queue");
7
8
  const query_string_1 = require("../../../client/query-string");
8
9
  const ovok_errors_1 = require("../../errors/ovok-errors");
@@ -13,6 +14,7 @@ const save_error_1 = require("./save-error");
13
14
  const signed_in_account_1 = require("./signed-in-account");
14
15
  const LATEST_OBSERVATIONS_PATH = "fhir/Observation/$lastn";
15
16
  const LATEST_PER_CODE = 1;
17
+ const PRECONDITION_FAILED = 412;
16
18
  /**
17
19
  * Builds, saves and reads measurements as FHIR Observations, with an offline queue.
18
20
  *
@@ -54,7 +56,11 @@ class MeasurementsResource {
54
56
  ? { status: "saved", response }
55
57
  : { status: "queued", queueId: queued.id };
56
58
  }
57
- /** Many readings, each main observation first, in as few requests as fit; a reading alone stays atomic. */
59
+ /**
60
+ * Many readings, each main observation first, in as few requests as fit. A request holding one reading is a
61
+ * transaction, atomic when the project enables FHIR transactions. A request holding several is two batches, main
62
+ * observations first: if it fails, some readings may be saved and others not, and saving them again is safe.
63
+ */
58
64
  async saveObservationGroups(groups, options = {}) {
59
65
  const { identifierSystems, replace, ...requestOptions } = options;
60
66
  const entryGroups = groups
@@ -62,9 +68,10 @@ class MeasurementsResource {
62
68
  .map((group) => (0, observation_bundle_utils_1.linkObservationMembers)(group).map((observation) => (0, offline_measurement_queue_1.entryForObservation)(observation, { identifierSystems, replace })));
63
69
  const owner = await this.currentOwnerKey();
64
70
  const responses = [];
65
- for (const request of (0, observation_bundle_utils_1.packObservationGroups)(entryGroups)) {
66
- const type = request.length === 1 ? "transaction" : "batch";
67
- responses.push(await this.send({ resourceType: "Bundle", type, entry: request.flat() }, requestOptions, owner));
71
+ for (const request of (0, observation_groups_1.packObservationGroups)(entryGroups)) {
72
+ responses.push(request.length === 1
73
+ ? await this.send({ resourceType: "Bundle", type: "transaction", entry: request.flat() }, requestOptions, owner)
74
+ : await this.sendReadings(request, requestOptions, owner));
68
75
  }
69
76
  return { resourceType: "Bundle", type: "batch-response", entry: responses.flatMap((response) => { var _a; return (_a = response.entry) !== null && _a !== void 0 ? _a : []; }) };
70
77
  }
@@ -101,10 +108,28 @@ class MeasurementsResource {
101
108
  }
102
109
  return params.patientId;
103
110
  }
104
- /** A reading split over several requests stops once another account signs in, so none of it lands elsewhere. */
111
+ /**
112
+ * A reading split over several requests stops once another account signs in, so none of it lands elsewhere. A
113
+ * transaction refused because its main observation matched several saved copies is sent again as batches.
114
+ */
105
115
  async send(bundle, options, owner) {
116
+ var _a;
117
+ try {
118
+ return await this.guarded((execute) => (0, observation_bundle_utils_1.executeObservationBundle)(bundle, execute), options, owner);
119
+ }
120
+ catch (error) {
121
+ if (bundle.type === "transaction" && error instanceof ovok_errors_1.OvokError && error.status === PRECONDITION_FAILED) {
122
+ return this.sendReadings([(_a = bundle.entry) !== null && _a !== void 0 ? _a : []], options, owner);
123
+ }
124
+ throw error;
125
+ }
126
+ }
127
+ sendReadings(groups, options, owner) {
128
+ return this.guarded((execute) => (0, observation_groups_1.executeReadingsBatch)(groups, execute), options, owner);
129
+ }
130
+ async guarded(run, options, owner) {
106
131
  try {
107
- return await (0, observation_bundle_utils_1.executeObservationBundle)(bundle, async (request) => {
132
+ return await run(async (request) => {
108
133
  await this.requireOwner(owner);
109
134
  return this.fhir.batch(request, options);
110
135
  });
@@ -6,5 +6,5 @@ import type { Observation } from "@medplum/fhirtypes";
6
6
  * @category measurements
7
7
  */
8
8
  export type BuildObservationsParams = GenerateObservationBodyParams;
9
- /** One measurement's Observations about `subject`, a reference such as `Patient/1`. */
9
+ /** One measurement's Observations about `subject`, a reference such as `Patient/1`; several end with their group. */
10
10
  export declare function buildObservations(params: BuildObservationsParams, subject: string): Observation[];
@@ -2,18 +2,27 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.buildObservations = buildObservations;
4
4
  const fhir_systems_1 = require("../../../client/observation/fhir-systems");
5
+ const observation_coding_1 = require("../../../client/observation/observation-coding");
6
+ const reading_group_1 = require("../../../client/observation/reading-group");
5
7
  const creator_1 = require("../../../client/observation/services/creator");
6
8
  const getDeviceObject_1 = require("../../../client/observation/utils/getDeviceObject");
7
- /** One measurement's Observations about `subject`, a reference such as `Patient/1`. */
9
+ /** One measurement's Observations about `subject`, a reference such as `Patient/1`; several end with their group. */
8
10
  function buildObservations(params, subject) {
9
- const service = creator_1.ObservationServiceCreator.getInstance().getService(params.measurement.measurementTypeKey);
11
+ const measurement = timedMeasurement(params.measurement, params.effectiveDateTime);
12
+ const service = creator_1.ObservationServiceCreator.getInstance().getService(measurement.measurementTypeKey);
10
13
  const device = (0, getDeviceObject_1.getDeviceObject)(params.device);
11
- const observations = fragmentsOf(service, params.measurement)
12
- .map((fragment) => observationOf(fragment, subject, device))
14
+ const readingFields = (0, observation_coding_1.readingStatusAndCategory)(measurement.measurementTypeKey);
15
+ const observations = fragmentsOf(service, measurement)
16
+ .map((fragment) => observationOf(fragment, subject, device, readingFields))
13
17
  .filter(hasValue)
14
18
  .map((observation) => datedAt(observation, params.effectiveDateTime));
15
- return params.sourceId ? namedAfterSource(observations, subject, params.sourceId) : observations;
19
+ const parts = (0, observation_coding_1.withDeviceUser)(observations, measurement.memorySlot);
20
+ const group = (0, reading_group_1.readingGroupOf)(measurement.measurementTypeKey, parts);
21
+ const reading = group ? [...parts, group] : parts;
22
+ return params.sourceId ? namedAfterSource(reading, subject, params.sourceId) : reading;
16
23
  }
24
+ /** The caller's time stands in for a measurement that carries none, so every observation of it shares one time. */
25
+ const timedMeasurement = (measurement, effectiveDateTime) => measurement.recordedAt || !effectiveDateTime ? measurement : { ...measurement, recordedAt: effectiveDateTime };
17
26
  /** Services without fragments describe their observations as parallel code, value and property lists. */
18
27
  const fragmentsOf = (service, measurement) => { var _a, _b; return (_b = (_a = service.generateObservationFragments) === null || _a === void 0 ? void 0 : _a.call(service, measurement)) !== null && _b !== void 0 ? _b : codeValueFragments(service, measurement); };
19
28
  const codeValueFragments = (service, measurement) => {
@@ -25,9 +34,9 @@ const codeValueFragments = (service, measurement) => {
25
34
  additionalProperties: additionalProperties[index],
26
35
  }));
27
36
  };
28
- const observationOf = (fragment, subject, device) => ({
37
+ const observationOf = (fragment, subject, device, readingFields) => ({
29
38
  resourceType: "Observation",
30
- status: "registered",
39
+ ...readingFields,
31
40
  subject: { reference: subject },
32
41
  device,
33
42
  ...fragment.value,
@@ -2,15 +2,14 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.isBundle = void 0;
4
4
  exports.saveErrorFrom = saveErrorFrom;
5
+ const bundle_entry_status_1 = require("../../../client/observation/bundle-entry-status");
5
6
  const ovok_errors_1 = require("../../errors/ovok-errors");
6
- const FAILED_STATUS = /^[45]/;
7
7
  const isBundle = (value) => typeof value === "object" && value !== null && value.resourceType === "Bundle";
8
8
  exports.isBundle = isBundle;
9
9
  /** A save's response that refused or left out an observation; a refused one gives its own status. */
10
10
  function saveErrorFrom(response) {
11
- var _a;
12
- const statuses = ((_a = response.entry) !== null && _a !== void 0 ? _a : []).map((entry) => { var _a, _b; return (_b = (_a = entry.response) === null || _a === void 0 ? void 0 : _a.status) !== null && _b !== void 0 ? _b : ""; });
13
- const refused = statuses.find((status) => FAILED_STATUS.test(status));
11
+ var _a, _b, _c;
12
+ const refused = (_c = (_b = ((_a = response.entry) !== null && _a !== void 0 ? _a : []).find(bundle_entry_status_1.isFailedEntry)) === null || _b === void 0 ? void 0 : _b.response) === null || _c === void 0 ? void 0 : _c.status;
14
13
  const message = refused
15
14
  ? `The server refused an observation of the reading: ${refused}.`
16
15
  : "The server's response left out an observation of the reading.";
@@ -77,20 +77,21 @@ class RealtimeSocket {
77
77
  this.waitingForPong = false;
78
78
  return;
79
79
  }
80
- if (!isSubscriptionStatus(message)) {
80
+ if (!isStatusBundle(message)) {
81
81
  socket.close();
82
82
  return;
83
83
  }
84
- if (message.type === "handshake") {
84
+ const [{ resource: status }, ...changes] = message.entry;
85
+ if (status.type === "handshake") {
85
86
  this.clearHandshakeTimer();
86
87
  this.onHandshake();
87
88
  return;
88
89
  }
89
- if (message.type === "heartbeat") {
90
+ if (status.type === "heartbeat") {
90
91
  return;
91
92
  }
92
- if (message.type === "event-notification") {
93
- this.handler({ ...message, type: "event-notification" });
93
+ if (status.type === "event-notification") {
94
+ this.handler({ ...status, type: "event-notification", resources: changedResources(changes) });
94
95
  }
95
96
  }
96
97
  socketClosed(socket) {
@@ -150,3 +151,9 @@ const isSubscriptionStatus = (value) => {
150
151
  typeof value.type === "string" &&
151
152
  typeof value.subscription.reference === "string");
152
153
  };
154
+ const isStatusBundle = (value) => value.resourceType === "Bundle" &&
155
+ Array.isArray(value.entry) &&
156
+ isRecord(value.entry[0]) &&
157
+ isSubscriptionStatus(value.entry[0].resource);
158
+ const isResource = (value) => isRecord(value) && typeof value.resourceType === "string";
159
+ const changedResources = (entries) => entries.flatMap((entry) => (isRecord(entry) && isResource(entry.resource) ? [entry.resource] : []));
@@ -1,4 +1,4 @@
1
- import type { SubscriptionStatus } from "@medplum/fhirtypes";
1
+ import type { Resource, SubscriptionStatus } from "@medplum/fhirtypes";
2
2
  /**
3
3
  * A notification that a resource matching a subscription changed.
4
4
  *
@@ -7,6 +7,8 @@ import type { SubscriptionStatus } from "@medplum/fhirtypes";
7
7
  export type RealtimeNotification = SubscriptionStatus & {
8
8
  /** Always `"event-notification"`. */
9
9
  type: "event-notification";
10
+ /** The changed resources sent with the notification, in the order the server sent them. */
11
+ resources: Resource[];
10
12
  };
11
13
  /**
12
14
  * Callback invoked for each realtime notification.