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

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 (54) 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/index.d.ts +1 -0
  41. package/dist/next/resources/auth/adopted-session.d.ts +30 -0
  42. package/dist/next/resources/auth/adopted-session.js +46 -0
  43. package/dist/next/resources/auth-resource.d.ts +16 -0
  44. package/dist/next/resources/auth-resource.js +21 -2
  45. package/dist/next/resources/cms/cms-resource.d.ts +8 -1
  46. package/dist/next/resources/cms/cms-resource.js +19 -6
  47. package/dist/next/resources/measurements/measurements-resource.d.ts +11 -2
  48. package/dist/next/resources/measurements/measurements-resource.js +31 -6
  49. package/dist/next/resources/measurements/observation-builder.d.ts +1 -1
  50. package/dist/next/resources/measurements/observation-builder.js +16 -7
  51. package/dist/next/resources/measurements/save-error.js +3 -4
  52. package/dist/next/resources/realtime/realtime-socket.js +12 -5
  53. package/dist/next/resources/realtime/realtime-types.d.ts +3 -1
  54. package/package.json +2 -2
@@ -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;
@@ -0,0 +1,13 @@
1
+ import { BundleEntry, Observation } from "@medplum/fhirtypes";
2
+ import { MeasurementTypeKey } from "./types/MeasurementTypeKey";
3
+ /** Identifies a group created for a reading saved before groups existed, by its first observation's id. */
4
+ export declare const READING_GROUP_OF_SYSTEM = "https://sdk.ovok.com/fhir/reading-group-of";
5
+ /** The measurement types whose readings get a group, for the code search that loads them. */
6
+ export declare const GROUPED_MEASUREMENT_TYPES: MeasurementTypeKey[];
7
+ /**
8
+ * The groups that readings saved before groups existed are missing: one for each first observation that later parts
9
+ * point at, that no group covers yet, and whose type has a group. Pass every observation of one patient's readings.
10
+ */
11
+ export declare const missingReadingGroups: (observations: readonly Observation[]) => Observation[];
12
+ /** Bundle entries that create each group only if none was created for its reading before. */
13
+ export declare const readingGroupEntries: (groups: readonly Observation[]) => BundleEntry<Observation>[];
@@ -0,0 +1,79 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readingGroupEntries = exports.missingReadingGroups = exports.GROUPED_MEASUREMENT_TYPES = exports.READING_GROUP_OF_SYSTEM = void 0;
4
+ const observation_coding_1 = require("./observation-coding");
5
+ const reading_group_1 = require("./reading-group");
6
+ const MeasurementTypeKey_1 = require("./types/MeasurementTypeKey");
7
+ const ObservationCode_1 = require("./types/ObservationCode");
8
+ const UrineAnalytes_1 = require("./types/UrineAnalytes");
9
+ /** Identifies a group created for a reading saved before groups existed, by its first observation's id. */
10
+ exports.READING_GROUP_OF_SYSTEM = "https://sdk.ovok.com/fhir/reading-group-of";
11
+ const TYPE_BY_FIRST_CODE = new Map([
12
+ [ObservationCode_1.ObservationCode.SYSTOLIC_BLOOD_PRESSURE, MeasurementTypeKey_1.MeasurementTypeKey.bloodPressure],
13
+ [ObservationCode_1.ObservationCode.OXYGEN_SATURATION, MeasurementTypeKey_1.MeasurementTypeKey.bloodOxygenPulseRate],
14
+ [ObservationCode_1.ObservationCode.ECG, MeasurementTypeKey_1.MeasurementTypeKey.ecg],
15
+ ...UrineAnalytes_1.URINE_ANALYTE_DEFINITIONS.map(({ code }) => [code, MeasurementTypeKey_1.MeasurementTypeKey.urineAnalysis]),
16
+ ]);
17
+ /** The measurement types whose readings get a group, for the code search that loads them. */
18
+ exports.GROUPED_MEASUREMENT_TYPES = [...new Set(TYPE_BY_FIRST_CODE.values())];
19
+ const referencedId = (reference) => { var _a; return (_a = reference === null || reference === void 0 ? void 0 : reference.match(/^Observation\/(.+)$/)) === null || _a === void 0 ? void 0 : _a[1]; };
20
+ const firstIdOf = (observation) => { var _a, _b; return referencedId((_b = (_a = observation.hasMember) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.reference); };
21
+ const codeOf = (observation) => { var _a, _b, _c; return (_c = (_b = (_a = observation.code) === null || _a === void 0 ? void 0 : _a.coding) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.code; };
22
+ /** The ids of first observations a group already points at. */
23
+ const groupedFirstIds = (observations) => new Set(observations
24
+ .filter(reading_group_1.isReadingGroup)
25
+ .flatMap((group) => { var _a; return (_a = group.hasMember) !== null && _a !== void 0 ? _a : []; })
26
+ .flatMap(({ reference }) => { var _a; return (_a = referencedId(reference)) !== null && _a !== void 0 ? _a : []; }));
27
+ /** Each first observation that later parts point at, with those parts, in saved order. */
28
+ const readingsByFirst = (observations) => {
29
+ var _a, _b;
30
+ const byId = new Map(observations.flatMap((observation) => (observation.id ? [[observation.id, observation]] : [])));
31
+ const readings = new Map();
32
+ for (const observation of observations) {
33
+ const first = byId.get((_a = firstIdOf(observation)) !== null && _a !== void 0 ? _a : "");
34
+ if (first && !(0, reading_group_1.isReadingGroup)(observation)) {
35
+ readings.set(first, [...((_b = readings.get(first)) !== null && _b !== void 0 ? _b : [first]), observation]);
36
+ }
37
+ }
38
+ return readings;
39
+ };
40
+ const groupFor = (type, parts) => {
41
+ var _a;
42
+ const group = (0, reading_group_1.readingGroupOf)(type, parts);
43
+ const firstId = (_a = parts[0]) === null || _a === void 0 ? void 0 : _a.id;
44
+ return group && firstId
45
+ ? {
46
+ ...group,
47
+ ...(0, observation_coding_1.readingStatusAndCategory)(type),
48
+ identifier: [{ system: exports.READING_GROUP_OF_SYSTEM, value: firstId }],
49
+ hasMember: parts.map(({ id }) => ({ reference: `Observation/${id}` })),
50
+ }
51
+ : undefined;
52
+ };
53
+ /**
54
+ * The groups that readings saved before groups existed are missing: one for each first observation that later parts
55
+ * point at, that no group covers yet, and whose type has a group. Pass every observation of one patient's readings.
56
+ */
57
+ const missingReadingGroups = (observations) => {
58
+ const grouped = groupedFirstIds(observations);
59
+ return [...readingsByFirst(observations)].flatMap(([first, parts]) => {
60
+ var _a;
61
+ const type = TYPE_BY_FIRST_CODE.get((_a = codeOf(first)) !== null && _a !== void 0 ? _a : "");
62
+ const group = type && first.id && !grouped.has(first.id) ? groupFor(type, parts) : undefined;
63
+ return group ? [group] : [];
64
+ });
65
+ };
66
+ exports.missingReadingGroups = missingReadingGroups;
67
+ /** Bundle entries that create each group only if none was created for its reading before. */
68
+ const readingGroupEntries = (groups) => groups.map((group) => {
69
+ var _a, _b, _c;
70
+ return ({
71
+ request: {
72
+ method: "POST",
73
+ url: "Observation",
74
+ ifNoneExist: `identifier=${encodeURIComponent(`${exports.READING_GROUP_OF_SYSTEM}|${(_c = (_b = (_a = group.identifier) === null || _a === void 0 ? void 0 : _a[0]) === null || _b === void 0 ? void 0 : _b.value) !== null && _c !== void 0 ? _c : ""}`)}`,
75
+ },
76
+ resource: group,
77
+ });
78
+ });
79
+ exports.readingGroupEntries = readingGroupEntries;
@@ -0,0 +1,14 @@
1
+ import { Coding, Observation } from "@medplum/fhirtypes";
2
+ import { MeasurementTypeKey } from "./types/MeasurementTypeKey";
3
+ /** The code of a reading's group: its LOINC panel where one exists, else Ovok's measurement-type code. */
4
+ export declare const readingGroupCoding: (type: MeasurementTypeKey) => Coding;
5
+ /** The code a reading of `type` is grouped under, as a code search takes it. */
6
+ export declare const readingGroupCode: (type: MeasurementTypeKey) => string;
7
+ /** The observation that groups a multi-value reading: a group code and no value of its own. */
8
+ export declare const isReadingGroup: (observation: Observation) => boolean;
9
+ /**
10
+ * The group observation of a reading made of several observations: it carries the reading's code, time and device,
11
+ * and its `hasMember` is filled with the parts when they are saved. A blood pressure's also holds the pressures as
12
+ * components, as the FHIR vital-signs blood-pressure profile expects. A reading of one observation has none.
13
+ */
14
+ export declare const readingGroupOf: (type: MeasurementTypeKey, parts: readonly Observation[]) => Observation | undefined;
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.readingGroupOf = exports.isReadingGroup = exports.readingGroupCode = exports.readingGroupCoding = void 0;
4
+ const fhir_systems_1 = require("./fhir-systems");
5
+ const MeasurementTypeKey_1 = require("./types/MeasurementTypeKey");
6
+ const ObservationCode_1 = require("./types/ObservationCode");
7
+ const BLOOD_PRESSURE_PANEL = {
8
+ system: fhir_systems_1.LOINC_SYSTEM,
9
+ code: "85354-9",
10
+ display: "Blood pressure panel with all children optional",
11
+ };
12
+ const URINE_DIPSTICK_PANEL = {
13
+ system: fhir_systems_1.LOINC_SYSTEM,
14
+ code: "24357-6",
15
+ display: "Urinalysis macro (dipstick) panel - Urine",
16
+ };
17
+ const PANEL_BY_TYPE = {
18
+ [MeasurementTypeKey_1.MeasurementTypeKey.bloodPressure]: BLOOD_PRESSURE_PANEL,
19
+ [MeasurementTypeKey_1.MeasurementTypeKey.urineAnalysis]: URINE_DIPSTICK_PANEL,
20
+ [MeasurementTypeKey_1.MeasurementTypeKey.uricAcid]: URINE_DIPSTICK_PANEL,
21
+ };
22
+ const PANEL_CODES = new Set([BLOOD_PRESSURE_PANEL.code, URINE_DIPSTICK_PANEL.code]);
23
+ /** The pressures a panel repeats as components, as the vital-signs profile requires; a share must cover both. */
24
+ const BLOOD_PRESSURE_COMPONENT_CODES = [
25
+ ObservationCode_1.ObservationCode.SYSTOLIC_BLOOD_PRESSURE,
26
+ ObservationCode_1.ObservationCode.DIASTOLIC_BLOOD_PRESSURE,
27
+ ];
28
+ /** The code of a reading's group: its LOINC panel where one exists, else Ovok's measurement-type code. */
29
+ const readingGroupCoding = (type) => { var _a; return (_a = PANEL_BY_TYPE[type]) !== null && _a !== void 0 ? _a : { system: fhir_systems_1.MEASUREMENT_TYPE_SYSTEM, code: type }; };
30
+ exports.readingGroupCoding = readingGroupCoding;
31
+ /** The code a reading of `type` is grouped under, as a code search takes it. */
32
+ const readingGroupCode = (type) => { var _a; return (_a = (0, exports.readingGroupCoding)(type).code) !== null && _a !== void 0 ? _a : type; };
33
+ exports.readingGroupCode = readingGroupCode;
34
+ const hasValue = (observation) => Object.keys(observation).some((key) => key.startsWith("value"));
35
+ const hasPanelCode = (observation) => { var _a, _b, _c; return (_c = (_b = (_a = observation.code) === null || _a === void 0 ? void 0 : _a.coding) === null || _b === void 0 ? void 0 : _b.some(({ system, code }) => system === fhir_systems_1.LOINC_SYSTEM && PANEL_CODES.has(code !== null && code !== void 0 ? code : ""))) !== null && _c !== void 0 ? _c : false; };
36
+ /** A measurement-type code without components; component readings such as baby sleep share the system. */
37
+ const hasTypeGroupCode = (observation) => {
38
+ var _a, _b, _c, _d;
39
+ return !((_a = observation.component) === null || _a === void 0 ? void 0 : _a.length) &&
40
+ ((_d = (_c = (_b = observation.code) === null || _b === void 0 ? void 0 : _b.coding) === null || _c === void 0 ? void 0 : _c.some(({ system }) => system === fhir_systems_1.MEASUREMENT_TYPE_SYSTEM)) !== null && _d !== void 0 ? _d : false);
41
+ };
42
+ /** The observation that groups a multi-value reading: a group code and no value of its own. */
43
+ const isReadingGroup = (observation) => !hasValue(observation) && (hasPanelCode(observation) || hasTypeGroupCode(observation));
44
+ exports.isReadingGroup = isReadingGroup;
45
+ const codeOf = (observation) => { var _a, _b, _c; return (_c = (_b = (_a = observation.code) === null || _a === void 0 ? void 0 : _a.coding) === null || _b === void 0 ? void 0 : _b[0]) === null || _c === void 0 ? void 0 : _c.code; };
46
+ const bloodPressureComponents = (parts) => BLOOD_PRESSURE_COMPONENT_CODES.flatMap((code) => {
47
+ const part = parts.find((observation) => codeOf(observation) === code);
48
+ return (part === null || part === void 0 ? void 0 : part.valueQuantity) ? [{ code: part.code, valueQuantity: part.valueQuantity }] : [];
49
+ });
50
+ const spanOf = (parts) => {
51
+ const periods = parts.flatMap((part) => (part.effectivePeriod ? [part.effectivePeriod] : []));
52
+ if (periods.length === 0) {
53
+ return undefined;
54
+ }
55
+ const starts = periods.flatMap(({ start }) => (start ? [start] : [])).sort();
56
+ const ends = periods.flatMap(({ end }) => (end ? [end] : [])).sort();
57
+ return { start: starts[0], end: ends[ends.length - 1] };
58
+ };
59
+ /**
60
+ * The group observation of a reading made of several observations: it carries the reading's code, time and device,
61
+ * and its `hasMember` is filled with the parts when they are saved. A blood pressure's also holds the pressures as
62
+ * components, as the FHIR vital-signs blood-pressure profile expects. A reading of one observation has none.
63
+ */
64
+ const readingGroupOf = (type, parts) => {
65
+ var _a;
66
+ const [first] = parts;
67
+ if (!first || parts.length < 2) {
68
+ return undefined;
69
+ }
70
+ const period = spanOf(parts);
71
+ const components = type === MeasurementTypeKey_1.MeasurementTypeKey.bloodPressure ? bloodPressureComponents(parts) : [];
72
+ const interpretation = (_a = parts.find((part) => { var _a; return (_a = part.interpretation) === null || _a === void 0 ? void 0 : _a.length; })) === null || _a === void 0 ? void 0 : _a.interpretation;
73
+ return {
74
+ resourceType: "Observation",
75
+ status: first.status,
76
+ ...(first.category ? { category: first.category } : {}),
77
+ code: { coding: [(0, exports.readingGroupCoding)(type)] },
78
+ subject: first.subject,
79
+ ...(first.device ? { device: first.device } : {}),
80
+ ...(period ? { effectivePeriod: period } : first.effectiveDateTime ? { effectiveDateTime: first.effectiveDateTime } : {}),
81
+ ...(components.length > 0 ? { component: components } : {}),
82
+ ...(interpretation ? { interpretation } : {}),
83
+ };
84
+ };
85
+ exports.readingGroupOf = readingGroupOf;
@@ -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
  /**
@@ -41,7 +41,8 @@ export type SeriesSummary = {
41
41
  /**
42
42
  * A series as observations: one per measured property, in `MEASUREMENT_FIELDS` order with the main one first, each
43
43
  * holding its values as `valueSampledData` across the series' `effectivePeriod`. They carry the same codes as a
44
- * single reading of that kind. Save them with `saveObservations`, which links the rest to the first. ECG recordings
44
+ * single reading of that kind, and a series of several properties ends with their group. Save them with
45
+ * `saveObservations`, which links the rest to the first. ECG recordings
45
46
  * keep their own path, `generateObservationBodiesByMeasurement`.
46
47
  */
47
48
  export declare const seriesObservations: ({ series, patientId, device, status, }: SeriesObservationParams) => Observation[];
@@ -1,6 +1,8 @@
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");
5
+ const reading_group_1 = require("./reading-group");
4
6
  const creator_1 = require("./services/creator");
5
7
  const getDeviceObject_1 = require("./utils/getDeviceObject");
6
8
  /** FHIR's mark for a slot with no value. */
@@ -11,10 +13,11 @@ const sampledData = (values, decimals) => values
11
13
  /**
12
14
  * A series as observations: one per measured property, in `MEASUREMENT_FIELDS` order with the main one first, each
13
15
  * holding its values as `valueSampledData` across the series' `effectivePeriod`. They carry the same codes as a
14
- * single reading of that kind. Save them with `saveObservations`, which links the rest to the first. ECG recordings
16
+ * single reading of that kind, and a series of several properties ends with their group. Save them with
17
+ * `saveObservations`, which links the rest to the first. ECG recordings
15
18
  * keep their own path, `generateObservationBodiesByMeasurement`.
16
19
  */
17
- const seriesObservations = ({ series, patientId, device, status = "registered", }) => {
20
+ const seriesObservations = ({ series, patientId, device, status = "final", }) => {
18
21
  const service = creator_1.ObservationServiceCreator.getInstance().getService(series.measurementTypeKey);
19
22
  const codes = service.getObservationCodes();
20
23
  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; }));
@@ -22,7 +25,7 @@ const seriesObservations = ({ series, patientId, device, status = "registered",
22
25
  start: series.start.toISOString(),
23
26
  end: new Date(series.start.getTime() + slots * series.periodMs).toISOString(),
24
27
  };
25
- return service.getFields().flatMap((field, index) => {
28
+ const parts = service.getFields().flatMap((field, index) => {
26
29
  const values = series.values[field.key];
27
30
  const code = codes[index];
28
31
  if (!code || !(values === null || values === void 0 ? void 0 : values.some((value) => value !== null))) {
@@ -30,19 +33,22 @@ const seriesObservations = ({ series, patientId, device, status = "registered",
30
33
  }
31
34
  return [{
32
35
  resourceType: "Observation",
36
+ ...(0, observation_coding_1.readingStatusAndCategory)(series.measurementTypeKey),
33
37
  status,
34
38
  subject: { reference: `Patient/${patientId}` },
35
39
  device: (0, getDeviceObject_1.getDeviceObject)(device),
36
40
  code,
37
41
  effectivePeriod,
38
42
  valueSampledData: {
39
- origin: { value: 0, unit: field.unit },
43
+ origin: (0, observation_coding_1.ucumQuantity)(0, field.unit),
40
44
  period: series.periodMs,
41
45
  dimensions: 1,
42
46
  data: sampledData(values, field.decimals),
43
47
  },
44
48
  }];
45
49
  });
50
+ const group = (0, reading_group_1.readingGroupOf)(series.measurementTypeKey, parts);
51
+ return group ? [...parts, group] : parts;
46
52
  };
47
53
  exports.seriesObservations = seriesObservations;
48
54
  /**
@@ -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;
@@ -1,8 +1,11 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.BloodPressureService = void 0;
3
+ exports.BloodPressureService = exports.BLOOD_PRESSURE_STATUS_URL = void 0;
4
4
  const MeasurementTypes_1 = require("../../../types/MeasurementTypes");
5
+ const fhir_systems_1 = require("../fhir-systems");
5
6
  const base_observation_service_1 = require("./base-observation-service");
7
+ /** The monitor's measurement status (movement, loose cuff), kept on the systolic observation. */
8
+ exports.BLOOD_PRESSURE_STATUS_URL = `${fhir_systems_1.OVOK_EXTENSION_BASE_URL}/blood-pressure-measurement-status`;
6
9
  class BloodPressureService extends base_observation_service_1.BaseObservationService {
7
10
  constructor() {
8
11
  super(...arguments);
@@ -78,11 +81,12 @@ class BloodPressureService extends base_observation_service_1.BaseObservationSer
78
81
  ];
79
82
  }
80
83
  getAdditionalProperties(measurement) {
81
- var _a;
82
- const properties = super.getAdditionalProperties(measurement);
84
+ const [systolic, ...rest] = super.getAdditionalProperties(measurement);
85
+ const { status } = this.getCastedMeasurement(measurement);
83
86
  return [
84
- ...properties,
85
- { effectiveDateTime: (_a = properties[0]) === null || _a === void 0 ? void 0 : _a.effectiveDateTime },
87
+ status ? { ...systolic, extension: [{ url: exports.BLOOD_PRESSURE_STATUS_URL, valueString: status }] } : systolic,
88
+ ...rest,
89
+ { effectiveDateTime: systolic === null || systolic === void 0 ? void 0 : systolic.effectiveDateTime },
86
90
  ];
87
91
  }
88
92
  getMeasurementDisplay(measurement) {
@@ -2,9 +2,9 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.respiratoryTherapyService = exports.babySleepService = void 0;
4
4
  const MeasurementTypes_1 = require("../../../types/MeasurementTypes");
5
+ const fhir_systems_1 = require("../fhir-systems");
5
6
  const base_observation_service_1 = require("./base-observation-service");
6
7
  const measurement_time_1 = require("./measurement-time");
7
- const MEASUREMENT_TYPE_SYSTEM = "https://sdk.ovok.com/fhir/CodeSystem/measurement-type";
8
8
  /** One observation that carries the device adapter's coded components as they are. */
9
9
  class ComponentObservationService extends base_observation_service_1.BaseObservationService {
10
10
  constructor(measurementTypeKey, measurementTypeName, code) {
@@ -58,7 +58,7 @@ class ComponentObservationService extends base_observation_service_1.BaseObserva
58
58
  coding: [{
59
59
  code: this.code,
60
60
  display: `${this.title} observation`,
61
- system: MEASUREMENT_TYPE_SYSTEM,
61
+ system: fhir_systems_1.MEASUREMENT_TYPE_SYSTEM,
62
62
  }],
63
63
  };
64
64
  }
@@ -1,4 +1,8 @@
1
1
  import { CodeableConcept } from "@medplum/fhirtypes";
2
2
  import { EcgMeasurement } from "../../../types/MeasurementTypes";
3
3
  import { ObservationFragment } from "../types/generate-observation-body/ObservationFragment";
4
+ /** Milliseconds between samples; without a recording duration the time base is unknown, so the ECG can't be saved. */
5
+ export declare const ecgSamplePeriodMs: ({ duration, diagramPoints }: EcgMeasurement) => number;
6
+ /** SampledData's space-separated values; a sample the device could not measure is "E". */
7
+ export declare const sampledDataOf: (samples: readonly number[]) => string;
4
8
  export declare const generateEcgObservationFragments: (measurement: EcgMeasurement, observationCodes: CodeableConcept[]) => ObservationFragment[];
@@ -1,47 +1,51 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.generateEcgObservationFragments = void 0;
3
+ exports.generateEcgObservationFragments = exports.sampledDataOf = exports.ecgSamplePeriodMs = void 0;
4
4
  const fhir_systems_1 = require("../fhir-systems");
5
+ const observation_coding_1 = require("../observation-coding");
5
6
  const measurement_time_1 = require("./measurement-time");
6
7
  const MAX_SEGMENT_DURATION_SECONDS = 5 * 60;
7
8
  const MAX_SAMPLED_DATA_CHARACTERS = 750000;
9
+ const MILLISECONDS_PER_SECOND = 1000;
10
+ const SAMPLE_DECIMALS = 3;
11
+ const ERROR_SAMPLE = "E";
12
+ const MILLIVOLT_ORIGIN = { value: 0, unit: "mV", system: fhir_systems_1.UCUM_SYSTEM, code: "mV" };
13
+ const DURATION_COMPONENT_SYSTEM = `${fhir_systems_1.OVOK_EXTENSION_BASE_URL}/observation-component`;
14
+ /** Milliseconds between samples; without a recording duration the time base is unknown, so the ECG can't be saved. */
15
+ const ecgSamplePeriodMs = ({ duration, diagramPoints }) => {
16
+ if (typeof duration !== "number" || !Number.isFinite(duration) || duration <= 0 || !(diagramPoints === null || diagramPoints === void 0 ? void 0 : diagramPoints.length)) {
17
+ throw new Error("An ECG needs its recording duration to be saved.");
18
+ }
19
+ return (duration * MILLISECONDS_PER_SECOND) / diagramPoints.length;
20
+ };
21
+ exports.ecgSamplePeriodMs = ecgSamplePeriodMs;
22
+ /** SampledData's space-separated values; a sample the device could not measure is "E". */
23
+ const sampledDataOf = (samples) => samples.map((sample) => (Number.isFinite(sample) ? String(Number(sample.toFixed(SAMPLE_DECIMALS))) : ERROR_SAMPLE)).join(" ");
24
+ exports.sampledDataOf = sampledDataOf;
8
25
  const generateEcgObservationFragments = (measurement, observationCodes) => {
9
26
  const fragments = [];
10
27
  const diagramPoints = measurement.diagramPoints;
11
28
  const recordedAt = (0, measurement_time_1.recordedAtOrNow)(measurement);
12
- const duration = typeof measurement.duration === "number" &&
13
- Number.isFinite(measurement.duration) &&
14
- measurement.duration > 0
15
- ? measurement.duration
16
- : undefined;
17
29
  if (diagramPoints === null || diagramPoints === void 0 ? void 0 : diagramPoints.length) {
18
- const maxSamplesForDuration = duration
19
- ? Math.max(1, Math.floor((MAX_SEGMENT_DURATION_SECONDS * diagramPoints.length) / duration))
20
- : diagramPoints.length;
30
+ const period = (0, exports.ecgSamplePeriodMs)(measurement);
31
+ const duration = measurement.duration;
32
+ const maxSamplesForDuration = Math.max(1, Math.floor((MAX_SEGMENT_DURATION_SECONDS * diagramPoints.length) / duration));
21
33
  const maxSamples = Math.min(maxSamplesForDuration, Math.max(1, Math.floor(MAX_SAMPLED_DATA_CHARACTERS / 7)));
22
34
  const recordingId = `ecg-${recordedAt.getTime()}-${diagramPoints.length}`;
23
35
  const ecgCode = observationCodes[0];
24
36
  for (let startIndex = 0, segmentIndex = 0; startIndex < diagramPoints.length; startIndex += maxSamples, segmentIndex++) {
25
37
  const segment = diagramPoints.slice(startIndex, startIndex + maxSamples);
26
- const segmentDuration = duration
27
- ? (duration * segment.length) / diagramPoints.length
28
- : segment.length / 1000;
29
- const segmentStart = new Date(recordedAt.getTime() +
30
- (duration
31
- ? (duration * startIndex * 1000) / diagramPoints.length
32
- : startIndex));
33
- const segmentEnd = new Date(segmentStart.getTime() + segmentDuration * 1000);
38
+ const segmentStart = new Date(recordedAt.getTime() + startIndex * period);
39
+ const segmentEnd = new Date(segmentStart.getTime() + segment.length * period);
34
40
  const firstId = recordingId;
35
41
  fragments.push({
36
42
  code: ecgCode,
37
43
  value: {
38
44
  valueSampledData: {
39
- origin: { value: 0, unit: "mV" },
40
- period: duration
41
- ? (duration * 1000) / diagramPoints.length
42
- : 1,
45
+ origin: MILLIVOLT_ORIGIN,
46
+ period,
43
47
  dimensions: 1,
44
- data: segment.map((sample) => Number(sample.toFixed(3))).join(" "),
48
+ data: (0, exports.sampledDataOf)(segment),
45
49
  },
46
50
  },
47
51
  additionalProperties: {
@@ -50,15 +54,11 @@ const generateEcgObservationFragments = (measurement, observationCodes) => {
50
54
  start: segmentStart.toISOString(),
51
55
  end: segmentEnd.toISOString(),
52
56
  },
53
- hasMember: segmentIndex === 0
54
- ? []
55
- : [{ reference: `Observation/${firstId}` }],
57
+ ...(segmentIndex === 0 ? {} : { hasMember: [{ reference: `Observation/${firstId}` }] }),
56
58
  ...(segmentIndex === 0 && measurement.diagnosticResult
57
59
  ? { interpretation: [{ text: measurement.diagnosticResult }] }
58
60
  : {}),
59
- ...(segmentIndex === 0 && duration !== undefined
60
- ? { component: [durationComponent(duration)] }
61
- : {}),
61
+ ...(segmentIndex === 0 ? { component: [durationComponent(duration)] } : {}),
62
62
  },
63
63
  });
64
64
  }
@@ -66,14 +66,7 @@ const generateEcgObservationFragments = (measurement, observationCodes) => {
66
66
  if (typeof measurement.heartRate === "number") {
67
67
  fragments.push({
68
68
  code: observationCodes[1],
69
- value: {
70
- valueQuantity: {
71
- value: Number(measurement.heartRate.toFixed(0)),
72
- unit: "bpm",
73
- code: "8867-4",
74
- system: fhir_systems_1.LOINC_SYSTEM,
75
- },
76
- },
69
+ value: { valueQuantity: (0, observation_coding_1.ucumQuantity)(Number(measurement.heartRate.toFixed(0)), "bpm") },
77
70
  additionalProperties: {
78
71
  effectiveDateTime: recordedAt.toISOString(),
79
72
  },
@@ -85,7 +78,7 @@ exports.generateEcgObservationFragments = generateEcgObservationFragments;
85
78
  const durationComponent = (duration) => ({
86
79
  code: {
87
80
  text: "measurement-duration",
88
- coding: [{ code: "measurement-duration" }],
81
+ coding: [{ system: DURATION_COMPONENT_SYSTEM, code: "measurement-duration" }],
89
82
  },
90
83
  id: "measurement-duration",
91
84
  valueQuantity: {
@@ -1,4 +1,4 @@
1
- import { Observation } from "@medplum/fhirtypes";
1
+ import { CodeableConcept, Observation } from "@medplum/fhirtypes";
2
2
  import { EcgMeasurement, Measurement, MeasurementTypeKey } from "../../../types/MeasurementTypes";
3
3
  import { ObservationFragment } from "../types/generate-observation-body/ObservationFragment";
4
4
  import { ObservationValue } from "../types/generate-observation-body/ObservationValue";
@@ -12,6 +12,8 @@ export declare class EcgService extends BaseObservationService<EcgMeasurement> {
12
12
  /** Expand long recordings into bounded, timestamped observations. */
13
13
  generateObservationFragments(measurement: Measurement): ObservationFragment[];
14
14
  getAdditionalProperties(measurement: Measurement): Partial<Observation>[];
15
+ /** The waveform is coded in the ISO/IEEE 11073 nomenclature, not LOINC. */
16
+ getObservationCodes(): CodeableConcept[];
15
17
  getMeasurementDisplay(measurement: Measurement): string;
16
18
  getObservationDisplay(observations: Observation[]): string | undefined;
17
19
  convertSamplesToMeasurement(): EcgMeasurement;