diff --git a/CHANGELOG.md b/CHANGELOG.md index 3065f652..0e7986b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Added +- IPS: clinical profiles have guided input - questions for the people filling a document in, about a section. A profile with any contains a Questionnaire (`#Q`) and has an `input-guide` extension (`http://www.healthintersections.com.au/fhir/StructureDefinition/input-guide`) for each guide: the Questionnaire, its questions' linkIds (made and kept by the server), the section (a Coding), and optionally the resource the answers make (`Condition:problem`, `Condition:diagnosis`, `Observation:vitals`, `MedicationStatement`, `AllergyIntolerance`) and its code. A question is text, a type (`display`, `boolean`, `quantity` with optional units, `date`, `choice` with its answer Codings) and optionally a definition (a path in a resource). The profile page shows them as a table grouped by section (IPS order, then the others), and the administrator adds, edits, deletes and moves them within a section a guide at a time, in a dialog. Uploads keep their guided input, and are refused if it is more than this or names a question the Questionnaire doesn't have - Keys: a key store for the whole server (`keystore`, off unless enabled; [library/keystore/README.md](library/keystore/README.md)). `/keys` lists public keys for anyone, and as a JWKS (`/keys/jwks.json`). A logged in user can upload public keys (PEM, a certificate, a JWK or JWKS, an OpenSSH line, DER), claiming a key id or not, and have the server make key pairs for them (EC P-256, EC P-384, RSA, Ed25519; one of each type), whose private keys the server keeps and signs with when a module asks; the administrator makes the system's own key pairs. Private keys are never uploaded (an upload with one is refused) and never given out. Owners revoke their keys, administrators revoke, delete and change key ids. A key is shown only as uploaded or created by its owner's display name. Limits: 10 uploads, then one a day; one key pair a day of each type. Private keys are in a database of their own (`keystore-private.db`, 0600). The daily report has a paragraph on them. Modules sign with `keystore.sign`/`signJws` and check with `verify`/`verifyJws`; there is no endpoint that signs what it is given - IPS: a first processing step, signatures, checks the document's signatures, with keys from the key store (by key id, or by the key a signature's certificate carries, which may have been revoked here), and shows what it found at the top of the analysis view. The check itself (`ips/signatures.js`) is not written yet, and says so - IPS: a document's source view has a banner with what can be done with the copy shown (the original, or the modified copy): download it as JSON, a ZIP, or a PDF with the document attached, and share it as an SHL or a VHL. The Download link at the top of the document page has moved there. `?download=1&source=modified` (and `?_format=json&source=modified`) gives the modified copy @@ -25,7 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - IPS: a Patient Comments tab on a document, for any comments the patient wishes to make about the accuracy or appropriateness of its content (a diagnosis in the problems section, say). One comment per document, in pure markdown (CommonMark): a comment with any HTML in it is refused; everyone can see it, anyone logged in can write, replace or remove it. It is kept apart from the document and its processing results, so processing again leaves it alone; deleting the document deletes it. To keep the document's tabs on one line, National Profiles is now Jurisdictions and AI Assessment is AI Check, and the tabs are a little closer together - IPS: when a document has patient comments, the source view's banner offers "Include Patient Comments", which, like the Sign choices, applies to every download (JSON, ZIP, PDF) and share (SHL, VHL). Any patient notes section (LOINC 51855-5) in the document is removed before signing; after signing, the comments go in as the Composition's first section - code LOINC 51855-5, title "Patient's Comments", the patient as author, and the comments as narrative (status `additional`), nothing else - so they are not signed. The signatures step checks a document's signatures with any patient notes section removed, for the same reason; and a patient notes section a document arrives with becomes its patient comment, converted to markdown (new dependency: turndown), when it has none yet. `{document}/signed` and `{document}/share` take `comments` - IPS: the source view's banner also offers "Regenerate narrative": the server generates the narrative of the copy downloaded or shared as the narrative step does (the narrative tab's Generated), before it is signed. `{document}/signed` and `{document}/share` take `narrative` -- IPS: `$document` on a stored document (`GET {project}/Bundle/{id}/$document`, or POST a Parameters resource) gives the API what the source view's banner gives a browser. Parameters `source` (original | modified), `user-sign` (as the owner of the API token; 401 without one, 409 with no key pair), `system-sign`, `patient-notes` (nothing added, and no error, when there are none) and `regenerate-narrative`. By `Accept` or `_format`: the JSON (the default), `application/zip`, `application/pdf`, or an SHL (`application/smart-health-link`) or VHL (`application/verified-health-link`) - the QR code as a PNG, with the link, manifest and expiry in `X-Health-Link*` headers. The ZIP and PDF are made on the server (`ips/export.js`; the PDF is the browser's content laid out as text in the standard fonts, with the document attached). Same rate limit as sharing. Its OperationDefinition is `ips/OperationDefinition-ips-document.json`, which the CapabilityStatement refers to on GitHub +- IPS: `$document` on a stored document (`GET {project}/Bundle/{id}/$document`, or POST a Parameters resource) gives the API what the source view's banner gives a browser. Parameters `source` (original | modified), `format-type`, `user-sign` (as the owner of the API token; 401 without one, 409 with no key pair), `system-sign`, `patient-notes` (nothing added, and no error, when there are none) and `regenerate-narrative`. What comes back: `format-type` (`json`, `pdf`, `zip`, `shl`, `vhl`) when given, whatever `Accept` says; otherwise `Accept` (or `_format`): the JSON (the default), `application/zip`, `application/pdf`, or `image/png` - a VHL's QR code. An SHL or VHL answer is the QR code (`image/png`), with the link, manifest and expiry in `X-Health-Link*` headers. The ZIP and PDF are made on the server (`ips/export.js`; the PDF is the browser's content laid out as text in the standard fonts, with the document attached). Same rate limit as sharing. Its OperationDefinition is `ips/OperationDefinition-ips-document.json`, which the CapabilityStatement refers to on GitHub - Registry: a code system resolution that finds nothing says, with `unknown-host`, when no server hosts any code system on the url's host, so clients needn't ask about each of that host's code systems (the tx ecosystem IG's Unknown Hosts) - tx: the ecosystem resolver remembers an `unknown-host` answer from the registry, and doesn't ask the registry about other code systems on that host for as long as it remembers a code system it was told nothing about; the cached answers viewer shows the hosts - tx: `$validate-code` on a CodeableConcept says what the ConceptMaps the server can find say about its codings together: for each coding, the maps from its code system to the code system of another coding (packages, libraries, tx-resources, and the maps code systems imply), read forwards, both ways round. A map that says the code is `not-related-to` the other coding, or that it has no map (`noMap`), is a warning; a map that relates it only to other codes is a hint (`TRANSLATION_WARNING_*`). Several maps that say the same thing are named in one message. This is the server side of the core validator's check, with the same messages @@ -34,6 +35,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- IPS: clinical profiles no longer have a full editor (Edit all, and the New profile page): a new profile is made from its title on the list page, renamed on its own page, and its rules and guided input edited there a row at a time +- IPS: the FHIRPath function `section(system, code)` without min and max is `1..1`, as it is in the Java `DocumentFunctions` (the validator's): a document with two of the same section has none, for a rule. It was no bounds. `entry()` and `entryIn()` are still `0..*` +- IPS: clinical profiles' required section rules no longer give the section a cardinality (a `section()` with bounds is now an other rule); instead three checkboxes say what the section must be - must be asked/known (`isKnown()`), must have supporting entries (`hasData()`), about the same Patient (`sameSubject()`). One check on its own is the rule (`Bundle.section(...).isKnown()`); more than one, or any with entries, go in a `where()`. `isKnown()`: no emptyReason, or a nil known one; `hasData()`: an emptyReason, or else entries; `sameSubject()` on a section: no focus, or the focus is the Composition's subject - in `ips/fhirpath-ips.js` (with `sameSubject([other])` on resources too), as in the Java `DocumentFunctions` +- IPS: clinical profiles' section choices include the Patient Story (LOINC 81338-6), and the editor lists the sections alphabetically, with "Another code..." last - tx: LOINC `$lookup` gives a property whose value is a LOINC code (COMPONENT and the other axes, parent, child, AnswerList, Answer, answers-for) the display of that code as its `description` - tx: the HTML view of a `$lookup` response puts its properties and designations in tables of their own, Properties and Designations, below the other parameters, with a column for each part (code, value, description, language, use and so on) instead of a bulleted list in each row. Its `name` parameter is shown as Code System name; a designation's use is shown as its display (Synonym, Fully specified name...), linked to `$lookup` on its code where the server has it, with the system and code in its title; and a Coding's code (a designation's use, say) is linked to `$lookup` on it in whatever code system it is from, if the server has that code system and the code is in it - not only in the code system the response is about - Home page and dashboard graphs: in a cluster, requests per minute, turnaround time, client cache and node blocking are one line for the cluster instead of one per process: requests and client concepts summed (the shared cache counted once), turnaround averaged over the requests, node blocking the worst process's. Private memory is still drawn per process diff --git a/CONFIGURATION.md b/CONFIGURATION.md index c8299d5a..f2d45627 100644 --- a/CONFIGURATION.md +++ b/CONFIGURATION.md @@ -117,7 +117,8 @@ with `--role`). Their settings are in `server.cluster`, documented with the arra [cluster.md](cluster.md): the launcher's (`workers`, `maxOutstanding`, `queueSeconds`, `recycleSeconds`, the fast lane, ...) under [The launcher](cluster.md#the-launcher-clusterjs), and what the processes share -(`sharedCache`, `cacheAffinity`, `sharedCacheMaxMB`, `sharedClosure`) under +(`sharedCache`, `cacheAffinity`, `sharedCacheMaxMB`, `sharedClosure`, and `workerModules`, for +workers that serve the rest module too) under [Options](cluster.md#options). With no role, `server.cluster` is ignored. The status panel's snapshot of every process (`statusSeconds`) is under [Status](cluster.md#status). @@ -288,6 +289,7 @@ Each module has its own entry under `modules`, documented with the module: | `packages` - package server | [packages/readme.md](packages/readme.md) | | `shl` - SMART Health Links | [shl/readme.md](shl/readme.md) | | `ips` - IPS documents | [ips/readme.md](ips/readme.md) | +| `rest` - FHIR REST servers | [rest/README.md](rest/README.md#configuration) | | `testing` - test reports | [testing/readme.md](testing/readme.md) | | `folder` | [folder/readme.md](folder/readme.md) | | `npmprojector` | [npmprojector/readme.md](npmprojector/readme.md) | diff --git a/README.md b/README.md index 48f982a9..770c3d60 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ This server provides a set of server-side services that are useful for the FHIR ## Under development, prototyping * [IPS](ips/readme.md) (`ips`) - collections of International Patient Summary documents, each with its own FHIR endpoint, processing (validation, terminology checks, translation, narrative, clinical profiles) and web pages +* [REST](rest/README.md) (`rest`) - database-backed FHIR RESTful servers (SQLite or MySQL): the interactions, search, batch and transaction, AuditEvents, each endpoint configured on its own ## On the back-burner diff --git a/cluster.js b/cluster.js index 6bb0a19a..c0801d40 100644 --- a/cluster.js +++ b/cluster.js @@ -47,7 +47,7 @@ const http = require('http'); const path = require('path'); const { spawn } = require('child_process'); -const { checkInstanceCode, bindAddress, connectAddress, ROLE_TRIM_ALLOCATOR, READY } = require('./library/role'); +const { checkInstanceCode, bindAddress, connectAddress, ROLE_TRIM_ALLOCATOR, READY, workerModules } = require('./library/role'); const { ClusterMetrics, METRIC, SNAPSHOT } = require('./library/cluster-metrics'); const { PendingCounts, COUNTS, COUNTS_INTERVAL_MS } = require('./library/cluster-counts'); const { CacheFanout, ASK: CACHES_ASK, DONE: CACHES_DONE } = require('./library/cluster-caches'); @@ -178,7 +178,9 @@ function loadSettings(argv, env, config, cpu = {}) { return { port, procs, - txPaths: (tx.endpoints || []).map(e => String(e.path).replace(/\/+$/, '')), + // the paths the workers serve: the tx endpoints, and the rest module's when the workers run + // it too (server.cluster.workerModules). Every other path goes to the master + txPaths: [...(tx.endpoints || []).map(e => String(e.path).replace(/\/+$/, '')), ...restPaths(config)], drainMs: Number(cluster.drainSeconds ?? DRAIN_MS / 1000) * 1000, maxOutstanding: Number(cluster.maxOutstanding ?? MAX_OUTSTANDING), queueMs: Number(cluster.queueSeconds ?? QUEUE_MS / 1000) * 1000, @@ -201,6 +203,19 @@ function loadSettings(argv, env, config, cpu = {}) { }; } +/** + * The rest module's endpoint paths, when the workers run it (server.cluster.workerModules): + * any process can serve any rest request, since all its state is in the database. + * @param {Object} config + */ +function restPaths(config) { + const rest = config.modules && config.modules.rest; + if (!rest || !rest.enabled || !workerModules(config).includes('rest')) { + return []; + } + return (rest.endpoints || []).map(e => String(e.path).replace(/\/+$/, '')).filter(p => p); +} + // the path after the tx endpoint ('' for the endpoint itself), or null if not a tx path function txRest(url, txPaths) { let p = String(url).split('?')[0]; diff --git a/cluster.md b/cluster.md index 2097b643..7f066fff 100644 --- a/cluster.md +++ b/cluster.md @@ -71,6 +71,7 @@ as before. | | master | tx-worker | |---|---|---| | tx module (`/r4`, `/r5` and the other endpoints) | yes (may also serve tx requests) | yes | +| rest module (its endpoints), with `"workerModules": ["rest"]` | yes, and its background jobs (schema migrations, expired searches, the closure, reindexing) | yes: every request, since all its state is in its databases | | Every other module (packages, xig, registry, publisher, shl, ips, ...) | yes | no | | Logins (`/auth`, [library/auth](library/auth/README.md)) | yes | the users and sessions are in one database every process reads: a login on one is one on all (with `auth.sessionSecret` set) | | `$closure` (the closure tables) | yes | no: routed to the master (yes, with [`sharedClosure`](#options)) | @@ -525,6 +526,7 @@ both only apply with a role: `node server.js` with no role ignores them. | `server.cluster.sharedCacheMaxMB` | 256 | With `sharedCache`: the most client resources (their JSON, in MB) the file holds, every endpoint's caches together. Past it, the caches least recently used are dropped whole, and a request with a dropped cache-id gets `404` `cache-id-unknown` (`CACHE_ID_EVICTED_SIZE`, which names the cap), so the client starts a new cache. 256: the largest IG Publisher cache session in a corpus of 2,817 from builds against tx.fhir.org held 3.5 MB of resources (p99 2.8 MB, median 55 KB), so this is about 70 times the largest; `cacheMaxTotalConcepts` gives one endpoint about 40 times the largest session's concepts, and this is that room for two busy endpoints. The file on disk is larger than what it holds (indexes, and the pages SQLite keeps for reuse). Each process logs the cap as it starts. 0: no cap. | | `server.cluster.sharedClosure` | false | Every tx process answers `$closure`, on the one closure database. | | `modules.tx.closure.writeRetries` | 10 | With `sharedClosure`: how many times an add is worked out again when another process changed the table first. | +| `server.cluster.workerModules` | `["tx"]` | The modules the workers run besides tx: `"rest"` is the only other one a worker can run. With it, the launcher sends the rest module's endpoints to any process, as it does tx requests. A rest endpoint on SQLite needs every process on this one machine (SQLite's locking is unreliable on network file systems); on MySQL the workers can be anywhere. See [rest/README.md](rest/README.md#clustering). | ### Shared cache diff --git a/config-template.json b/config-template.json index 02dada68..f5d11aa2 100644 --- a/config-template.json +++ b/config-template.json @@ -556,6 +556,27 @@ "autoLoadPackages": true // , "profiles": ["http://hl7.org/fhir/uv/ips/StructureDefinition/Bundle-uv-ips"] } + }, + // Database-backed FHIR RESTful servers. See rest/README.md. config.json says only where + // each endpoint is and which database it uses: everything else about an endpoint is kept + // in its own database. Users get the rest read / write / manage roles per endpoint + "rest": { + "enabled": false, + "endpoints": [ + { + "path": "/fhir/r4", + // fixed when the database is made + "fhirVersion": "4.0.1", + // a SQLite file (relative paths resolve under the databases directory), or MySQL: + // { "type": "mysql", "host": "localhost", "database": "fhir_r4", "user": "fhirsmith", + // "passwordEnv": "FHIR_R4_DB_PASSWORD" } - never a password here: passwordEnv names + // an environment variable, passwordFile a file only the server can read + "database": { "type": "sqlite", "file": "rest/fhir-r4.db" }, + // settings written into a new database (rest/README.md, "Settings"); after that the + // database's own values are used + "initialSettings": { "name": "FHIRsmith R4 test server", "anonymous": "read", "txServer": "/tx/r4" } + } + ] } } } \ No newline at end of file diff --git a/ips/OperationDefinition-ips-document.json b/ips/OperationDefinition-ips-document.json index 57987b29..184352aa 100644 --- a/ips/OperationDefinition-ips-document.json +++ b/ips/OperationDefinition-ips-document.json @@ -9,10 +9,12 @@ "kind": "operation", "date": "2026-11-22", "publisher": "Health Intersections Pty Ltd (FHIRsmith)", - "description": "Returns a document stored in a FHIRsmith IPS project as the web page's source view gives it for download or sharing: optionally with the narrative regenerated, signed by the user and/or the system, and with the patient's comments added - in that order. Any existing patient notes section (LOINC 51855-5) is removed before signing, and the patient's comments are added after signing, as the Composition's first section (LOINC 51855-5), so they are not signed.\n\nThe response is chosen by the Accept header, or by _format (a short name or the mime type):\n\n* application/fhir+json or application/json (json - the default): the document\n* application/zip (zip): a ZIP holding the document as {name}.json\n* application/pdf (pdf): a PDF of the document's narrative, with the document attached as {name}.json\n* application/smart-health-link (shl): the document shared as a SMART Health Link; the response is the QR code as a PNG, with the link in the X-Health-Link header, the manifest URL in X-Health-Link-Manifest, and the expiry in X-Health-Link-Expires\n* application/verified-health-link (vhl): the same, as a Verifiable Health Link (GDHCN)\n\nAnything else is 406. Errors are OperationOutcomes. $document shares the rate limit of the web page's sharing and signed downloads.", + "description": "Returns a document stored in a FHIRsmith IPS project as the web page's source view gives it for download or sharing: optionally with the narrative regenerated, signed by the user and/or the system, and with the patient's comments added - in that order. Any existing patient notes section (LOINC 51855-5) is removed before signing, and the patient's comments are added after signing, as the Composition's first section (LOINC 51855-5), so they are not signed.\n\nWhat comes back is chosen by the format-type parameter, when it is given; otherwise by the Accept header (or _format, which takes the same mime types):\n\n* json - application/fhir+json or application/json (the default): the document\n* zip - application/zip: a ZIP holding the document as {name}.json\n* pdf - application/pdf: a PDF of the document's narrative, with the document attached as {name}.json\n* vhl - image/png: the document shared as a Verifiable Health Link (GDHCN); the response is the QR code as a PNG, with what it carries in the X-Health-Link header, the manifest URL in X-Health-Link-Manifest, and the expiry in X-Health-Link-Expires\n* shl - image/png, with format-type=shl: the same, as a SMART Health Link\n\nAccept: image/png without format-type gives a VHL. Anything else is 406. Errors are OperationOutcomes. $document shares the rate limit of the web page's sharing and signed downloads.", "affectsState": false, "code": "document", - "resource": ["Bundle"], + "resource": [ + "Bundle" + ], "system": false, "type": false, "instance": true, @@ -25,6 +27,14 @@ "documentation": "original (the default): the document as submitted; modified: the copy the processing pipeline made (translations, generated narrative, terminology checks). 409 if the document has not been processed yet", "type": "code" }, + { + "name": "format-type", + "use": "in", + "min": 0, + "max": "1", + "documentation": "What to return: json (the document), pdf, zip, or a QR code (image/png) - shl (a SMART Health Link) or vhl (a Verifiable Health Link, the default for a QR code). When given, it decides, whatever the Accept header (or _format) says", + "type": "code" + }, { "name": "user-sign", "use": "in", diff --git a/ips/fhirpath-ips.js b/ips/fhirpath-ips.js index bcb24887..a5d3004c 100644 --- a/ips/fhirpath-ips.js +++ b/ips/fhirpath-ips.js @@ -34,8 +34,27 @@ * usually asks a terminology server - asynchronously, so the evaluation must be * (evaluateAsync); answers are best cached (membership.js). * - * min and max are optional (together): with neither, there is no constraint; max may - * be '*'. Being outside the bounds is not an error - the item adds nothing. + * isKnown(), hasData() + * The input: sections. isKnown(): each has no emptyReason, or a nil known one + * (list-empty-reason#nilknown) - any other emptyReason is not known. hasData(): each has an + * emptyReason, or else entries. Empty on no input; false for an item that isn't a section + * of a Composition (the one above it, or the document's). + * + * sameSubject([other]) + * On a section: true when it has no focus, otherwise whether the focus is the subject of + * other - or, without other, of its Composition. On a resource: whether its subject (or + * patient) is other's - or, without other, the document's Composition's (the evaluation + * must be on a Bundle of type document). Empty when the input isn't one item, other is + * given but isn't one item, or a subject is missing (or more than one). References are the + * same when their reference strings are identical (both having one), else when their + * identifiers' system and value are (both having one); otherwise not. (other is evaluated + * as fhirpath.js does a function's argument, from the root: use %resource.) + * + * These are the Java DocumentFunctions' (org.hl7.fhir.core), which the validator runs. + * + * min and max are optional (together): with neither, section() is 1..1 (one such section: + * two of the same is none) and entry() and entryIn() are 0..* (no constraint), as in the Java + * DocumentFunctions; max may be '*'. Being outside the bounds is not an error - the item adds nothing. * * References are resolved in the Bundle the section is in: found by walking up from the * section, or else the Bundle the expression was evaluated on (the evaluation's @@ -66,10 +85,13 @@ function num(v) { return v && typeof v === 'object' && typeof v.toNumber === 'function' ? v.toNumber() : v; } -/** min and max from the arguments: min an Integer, max an Integer or '*'. */ -function bounds(fnName, min, max) { +/** + * min and max from the arguments: min an Integer, max an Integer or '*'; without them, the + * function's default (section(): 1..1; the others: 0..*), as the Java DocumentFunctions has them. + */ +function bounds(fnName, min, max, defaults = { min: 0, max: Infinity }) { if (min === undefined) { - return { min: 0, max: Infinity }; + return { ...defaults }; } min = num(min); if (!Number.isInteger(min) || min < 0) { @@ -307,13 +329,73 @@ function membersOf(ctx, fnName, nodes, url, membership) { * Composition, it returns the resource or null. membership: whether a CodeableConcept is * in a value set (a canonical) - without it, entryIn() and resourcesIn() find nothing */ +// ---- the section checks, and sameSubject() -------------------------------------------------- + +const LIST_EMPTY_REASON = 'http://terminology.hl7.org/CodeSystem/list-empty-reason'; + +/** Whether data is one of a Composition's sections, at any depth (by identity). */ +function isSectionOf(comp, data) { + const walk = (list) => Array.isArray(list) && list.some(s => s === data || (isObject(s) && walk(s.section))); + return isObject(comp) && walk(comp.section); +} + +/** + * The Composition an item is a section of, at any depth: the one above it, or the document's + * the evaluation is on (or the Composition it is on) - null when the item isn't a section of one. + */ +function sectionComposition(ctx, item) { + const data = valData(item); + if (!isObject(data) || data.resourceType) { + return null; + } + const above = item instanceof ResourceNode ? ancestor(item, 'Composition') : null; + if (above && isSectionOf(valData(above), data)) { + return valData(above); + } + const roots = Array.isArray(ctx.dataRoot) ? ctx.dataRoot : [ctx.dataRoot]; + for (const r of roots) { + const comp = compositionNode(ctx, r); + if (comp && isSectionOf(valData(comp), data)) { + return valData(comp); + } + } + return null; +} + +/** A resource's subject (or patient), when it has one: null when it has neither, or more than one (R5+ Composition.subject repeats). */ +function subjectOf(resource) { + if (!isObject(resource)) { + return null; + } + const s = resource.subject !== undefined ? resource.subject : resource.patient; + const list = Array.isArray(s) ? s : (s === undefined ? [] : [s]); + return list.length === 1 && isObject(list[0]) ? list[0] : null; +} + +/** + * Whether two references are to the same thing: identical reference strings, when both have one; + * else, when both have an identifier, the same system and value; otherwise false. + */ +function sameReference(a, b) { + const refA = typeof a.reference === 'string' ? a.reference : ''; + const refB = typeof b.reference === 'string' ? b.reference : ''; + if (refA && refB) { + return refA === refB; + } + if (isObject(a.identifier) && isObject(b.identifier)) { + const value = a.identifier.value; + return typeof value === 'string' && value !== '' && value === b.identifier.value && a.identifier.system === b.identifier.system; + } + return false; +} + function ipsFunctions(options = {}) { const resolve = typeof options.resolve === 'function' ? options.resolve : null; const membership = typeof options.membership === 'function' ? options.membership : () => false; function section(inputs, system, code, min, max) { const ctx = this; - const b = bounds('section', min, max); + const b = bounds('section', min, max, { min: 1, max: 1 }); const out = []; for (const item of inputs) { const comp = compositionNode(ctx, item); @@ -367,12 +449,75 @@ function ipsFunctions(options = {}) { const arity = { 2: ['String', 'String'], 4: ['String', 'String', 'Integer', 'Any'] }; // internalStructures: the input and output are nodes, so the paths (and the Bundle a // section is in) are known; and fhirpath.js calls the function with the context as this + // isKnown(): each input a section with no emptyReason, or a nil known one + function isKnown(inputs) { + if (inputs.length === 0) { + return []; + } + return [inputs.every(item => { + if (!sectionComposition(this, item)) { + return false; + } + const reason = valData(item).emptyReason; + return reason === undefined || hasCoding(reason, LIST_EMPTY_REASON, 'nilknown'); + })]; + } + + // hasData(): each input a section with an emptyReason, or else entries + function hasData(inputs) { + if (inputs.length === 0) { + return []; + } + return [inputs.every(item => { + if (!sectionComposition(this, item)) { + return false; + } + const s = valData(item); + return s.emptyReason !== undefined || (Array.isArray(s.entry) && s.entry.length > 0); + })]; + } + + // sameSubject([other]): as the Java DocumentFunctions.sameSubject + function sameSubject(inputs, other) { + if (inputs.length !== 1) { + return []; + } + if (other !== undefined && other.length !== 1) { + return []; + } + const item = inputs[0]; + const comp = sectionComposition(this, item); + if (comp) { + // a section: its focus, if it has one, against the Composition's subject (or other's) + const focus = valData(item).focus; + if (!isObject(focus)) { + return [true]; + } + const target = subjectOf(other !== undefined ? valData(other[0]) : comp); + return target ? [sameReference(focus, target)] : []; + } + let o; + if (other !== undefined) { + o = valData(other[0]); + } else { + const bundle = rootBundle(this); + const doc = bundle ? valData(bundle) : null; + o = doc && doc.type === 'document' ? valData(compositionNode(this, bundle)) : null; + } + const a = subjectOf(valData(item)); + const b = subjectOf(o); + return a && b ? [sameReference(a, b)] : []; + } + return { section: { fn: section, arity, internalStructures: true }, entry: { fn: entry, arity, internalStructures: true }, resources: { fn: resources, arity: { 2: ['String', 'String'], 3: ['String', 'String', 'String'] }, internalStructures: true }, entryIn: { fn: entryIn, arity: { 1: ['String'], 3: ['String', 'Integer', 'Any'] }, internalStructures: true }, - resourcesIn: { fn: resourcesIn, arity: { 1: ['String'], 2: ['String', 'String'] }, internalStructures: true } + resourcesIn: { fn: resourcesIn, arity: { 1: ['String'], 2: ['String', 'String'] }, internalStructures: true }, + isKnown: { fn: isKnown, arity: { 0: [] }, internalStructures: true }, + hasData: { fn: hasData, arity: { 0: [] }, internalStructures: true }, + sameSubject: { fn: sameSubject, arity: { 0: [], 1: ['Any'] }, internalStructures: true } }; } diff --git a/ips/ips.js b/ips/ips.js index 243df3ba..937aa30f 100644 --- a/ips/ips.js +++ b/ips/ips.js @@ -103,19 +103,14 @@ function isOn(v) { // its OperationDefinition (ips/OperationDefinition-ips-document.json), where it is on GitHub const DOCUMENT_OPERATION_DEFINITION = 'https://github.com/HealthIntersections/FHIRsmith/blob/main/ips/OperationDefinition-ips-document.json'; -// what $document gives, by the name _format takes (a short name, or the mime type) -const DOCUMENT_FORMATS = { - json: 'application/fhir+json', - zip: 'application/zip', - pdf: 'application/pdf', - shl: 'application/smart-health-link', - vhl: 'application/verified-health-link' -}; +// what $document gives (format-type), and the mime types (Accept, _format) that ask for each: +// image/png is a QR code - a VHL, unless format-type says shl +const DOCUMENT_FORMAT_TYPES = ['json', 'pdf', 'zip', 'shl', 'vhl']; const DOCUMENT_MIME = { - 'application/fhir+json': 'json', 'application/json': 'json', 'fhir+json': 'json', '*/*': 'json', 'application/*': 'json', - 'application/zip': 'zip', 'application/pdf': 'pdf', - 'application/smart-health-link': 'shl', 'application/verified-health-link': 'vhl' + 'application/fhir+json': 'json', 'application/json': 'json', 'fhir+json': 'json', json: 'json', '*/*': 'json', 'application/*': 'json', + 'application/zip': 'zip', 'application/pdf': 'pdf', 'image/png': 'vhl' }; +const DOCUMENT_ACCEPTS = 'application/fhir+json (or application/json), application/zip, application/pdf, or image/png'; const DOCUMENT_BOOLEANS = { 'user-sign': 'userSign', 'system-sign': 'systemSign', 'patient-notes': 'patientNotes', 'regenerate-narrative': 'regenerateNarrative' }; // the outcome code for each status a copy can fail with const OUTCOME_CODES = { 401: 'login', 404: 'not-supported', 409: 'conflict', 422: 'processing', 429: 'throttled', 503: 'transient' }; @@ -125,7 +120,7 @@ const OUTCOME_CODES = { 401: 'login', 404: 'not-supported', 409: 'conflict', 422 * @returns {{source: string, userSign: boolean, systemSign: boolean, patientNotes: boolean, regenerateNarrative: boolean, problems: string[]}} */ function documentParameters(req) { - const out = { source: 'original', userSign: false, systemSign: false, patientNotes: false, regenerateNarrative: false, problems: [] }; + const out = { source: 'original', formatType: null, userSign: false, systemSign: false, patientNotes: false, regenerateNarrative: false, problems: [] }; const given = []; if (req.method === 'POST') { let b = req.body; @@ -159,6 +154,12 @@ function documentParameters(req) { } else { out.problems.push(`source is original or modified, not '${v}'`); } + } else if (k === 'format-type') { + if (DOCUMENT_FORMAT_TYPES.includes(v)) { + out.formatType = v; + } else { + out.problems.push(`format-type is ${DOCUMENT_FORMAT_TYPES.join(', ')}, not '${v}'`); + } } else if (DOCUMENT_BOOLEANS[k]) { if (v === true || v === 'true') { out[DOCUMENT_BOOLEANS[k]] = true; @@ -166,17 +167,21 @@ function documentParameters(req) { out.problems.push(`${k} is true or false, not '${v}'`); } } else { - out.problems.push(`$document has no parameter '${k}' (it takes source, ${Object.keys(DOCUMENT_BOOLEANS).join(', ')})`); + out.problems.push(`$document has no parameter '${k}' (it takes source, format-type, ${Object.keys(DOCUMENT_BOOLEANS).join(', ')})`); } } return out; } -/** What $document should give: _format (a short name or mime type), else Accept (by preference). @returns {string|null} */ +/** + * What $document should give, when format-type doesn't say: _format (a mime type, or json), else + * Accept (by preference). image/png is a VHL's QR code (format-type=shl for an SHL's). + * @returns {string|null} json, zip, pdf or vhl; null for nothing it gives + */ function documentFormat(req) { const f = typeof req.query._format === 'string' ? req.query._format.trim().toLowerCase().replace(/ /g, '+') : ''; if (f) { - return DOCUMENT_FORMATS[f] ? f : (DOCUMENT_MIME[f] || null); + return DOCUMENT_MIME[f] || null; } const accept = req.get('Accept'); if (!accept) { @@ -635,15 +640,21 @@ class IpsModule { r.get('/lookup', this.session, adminJson, ...this.lookups, h('lookup', (req, res) => this.systemLookup(req, res))); r.get('/lookup-vs', this.session, adminJson, ...this.lookups, h('lookup', (req, res) => this.valueSetLookup(req, res))); r.get('/StructureDefinition', ...this.web, h('profiles', (req, res) => this.profileList(req, res))); - r.get('/StructureDefinition/new', this.session, this.csrf, admin, h('profiles', (req, res) => this.profileEditor(req, res, null))); r.post('/StructureDefinition', this.sameOrigin, this.session, json, this.csrf, adminJson, h('profiles', (req, res) => this.profileSave(req, res, null))); r.get('/StructureDefinition/:id', profile, ...this.web, h('profile', (req, res) => this.profileRead(req, res))); - r.get('/StructureDefinition/:id/edit', profile, this.session, this.csrf, admin, h('profile', (req, res) => this.profileEditor(req, res, req.profile))); + // an old link to the full editor (there is no full editor now): the profile's page + r.get('/StructureDefinition/:id/edit', profile, (req, res) => res.redirect(`${req.baseUrl}/StructureDefinition/${req.profile.id}`)); + r.post('/StructureDefinition/:id/title', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => this.profileRename(req, res))); r.post('/StructureDefinition/:id', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.profileSave(req, res, req.profile))); // one constraint at a time, from the profile's page: add, edit (keeping its key), delete r.post('/StructureDefinition/:id/constraint', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.constraintSave(req, res, null))); r.post('/StructureDefinition/:id/constraint/:key', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.constraintSave(req, res, req.params.key))); r.post('/StructureDefinition/:id/constraint/:key/delete', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => this.constraintDelete(req, res))); + // guided input, one guide at a time: add, edit, delete, and move up or down in its section + r.post('/StructureDefinition/:id/guide', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.guideSave(req, res, null))); + r.post('/StructureDefinition/:id/guide/:n', profile, this.sameOrigin, this.session, json, this.csrf, adminJson, h('profile', (req, res) => this.guideSave(req, res, req.params.n))); + r.post('/StructureDefinition/:id/guide/:n/delete', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => this.guideDelete(req, res))); + r.post('/StructureDefinition/:id/guide/:n/move', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => this.guideMove(req, res))); r.post('/StructureDefinition/:id/delete', profile, this.sameOrigin, this.session, this.form, this.csrf, admin, h('profile', (req, res) => { this.store.deleteProfile(req.profileId); res.redirect(req.baseUrl + '/StructureDefinition'); @@ -1715,7 +1726,8 @@ class IpsModule { /** * $document on a stored document (GET, or POST with a Parameters resource): the document as the * source view's banner gives it - signed, with the patient's comments, the narrative regenerated - * (preparedCopy) - as JSON, a ZIP, a PDF, or an SHL/VHL QR code (a PNG), by Accept or _format. + * (preparedCopy) - as JSON, a ZIP, a PDF, or an SHL/VHL QR code (image/png), by the format-type + * parameter, else _format or Accept (image/png is a VHL's QR code). * Its OperationDefinition is ips/OperationDefinition-ips-document.json. */ async documentOperation(req, res) { @@ -1728,9 +1740,10 @@ class IpsModule { if (p.problems.length > 0) { return this.sendOutcome(res, 400, 'invalid', p.problems); } - const format = documentFormat(req); + // format-type, when given, decides (over Accept and _format) + const format = p.formatType || documentFormat(req); if (!format) { - return this.sendOutcome(res, 406, 'not-supported', `$document gives ${Object.keys(DOCUMENT_FORMATS).map(k => DOCUMENT_FORMATS[k]).join(', ')}: not ${req.query._format || req.get('Accept')}`); + return this.sendOutcome(res, 406, 'not-supported', `$document gives ${DOCUMENT_ACCEPTS}: not ${req.query._format || req.get('Accept')} (or use format-type)`); } const modified = p.source === 'modified'; const doc = modified ? row.analysed : row.bundle; @@ -2540,8 +2553,9 @@ class IpsModule { const ctx = { ...this.ctx(req, res), valueSetTitle: (url) => this.valueSetTitle(url), profileTitle: (url) => this.profileTitle(url) }; // the administrator edits the rows in place, a row at a time const editor = ctx.user?.isAdmin ? { - constraints: this.editorConstraints(sd), - sections: profiles.IPS_SECTIONS, systems: profiles.SYSTEMS, resourceTypes: profiles.RESOURCE_TYPES, sectionSystem: editorSchema.LOINC, canLookup: !!this.tx + constraints: this.editorConstraints(sd), guides: profiles.guidesOf(sd), + sections: profiles.IPS_SECTIONS, systems: profiles.SYSTEMS, resourceTypes: profiles.RESOURCE_TYPES, sectionSystem: editorSchema.LOINC, canLookup: !!this.tx, + questionTypes: profiles.QUESTION_TYPES, guideResources: profiles.GUIDE_RESOURCES } : null; this.sendHtml(res, `Clinical Profile: ${sd.title}`, render.renderProfile(sd, ctx, editor), Date.now(), req); } @@ -2570,23 +2584,15 @@ class IpsModule { return vs ? (vs.title || vs.name || null) : null; } - /** The editor, for a new profile or an existing one. */ + /** A profile's constraints, with the shapes the profile page's editor shows them in. */ editorConstraints(sd) { return profiles.constraintsOf(sd).map(c => ({ ...c, shape: profiles.parseShape(c.expression), rshape: profiles.parseResourceShape(c.expression) })); } - profileEditor(req, res, sd) { - const constraints = this.editorConstraints(sd); - this.sendHtml(res, sd ? `Edit Clinical Profile: ${sd.title}` : 'New Clinical Profile', - render.renderProfileEditor(sd, this.ctx(req, res), { - profile: { id: sd ? sd.id : null, title: sd ? sd.title : '', constraints }, - sections: profiles.IPS_SECTIONS, systems: profiles.SYSTEMS, resourceTypes: profiles.RESOURCE_TYPES, sectionSystem: editorSchema.LOINC, canLookup: !!this.tx - }), Date.now(), req); - } - /** - * Save a profile from the editor ({title, constraints}), or a new one from an uploaded - * StructureDefinition ({upload}). 200/201 with {id, url}, or 422 with {problems}. + * Save a profile ({title, constraints[, guides]} - a new one can be just a title; without guides, + * a profile keeps its own), or a new one from an uploaded StructureDefinition ({upload}). + * 200/201 with {id, url}, or 422 with {problems}. */ profileSave(req, res, previous) { const body = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {}; @@ -2602,12 +2608,13 @@ class IpsModule { input = up.input; } const checked = profiles.checkInput(input, previous); - if (checked.problems.length) { - return res.status(422).json({ problems: checked.problems }); + const guided = profiles.checkGuides(input.guides !== undefined ? input.guides : profiles.guidesOf(previous), previous); + if (checked.problems.length || guided.problems.length) { + return res.status(422).json({ problems: [...checked.problems, ...guided.problems] }); } const id = previous ? previous.id.substring('profile-'.length) : profiles.newId(); const url = previous ? previous.url : `${this.baseUrl(req)}/StructureDefinition/profile-${id}`; - const sd = profiles.build({ id, url, title: checked.title, constraints: checked.constraints }); + const sd = profiles.build({ id, url, title: checked.title, constraints: checked.constraints, guides: guided.guides }); this.store.saveProfile(id, sd); this.log.info(`IPS module: clinical profile ${sd.id} (${sd.title}) ${previous ? 'saved' : (body.upload !== undefined ? 'uploaded' : 'created')}, ${checked.constraints.length} constraints`); res.status(previous ? 200 : 201).json({ id: sd.id, url: `${req.baseUrl}/StructureDefinition/${sd.id}` }); @@ -2656,8 +2663,97 @@ class IpsModule { } saveConstraints(previous, constraints) { + this.saveProfileParts(previous, { constraints }); + } + + /** Save a profile with some of its parts changed: title, constraints, guides (each as it was when not given). */ + saveProfileParts(previous, parts) { const id = previous.id.substring('profile-'.length); - this.store.saveProfile(id, profiles.build({ id, url: previous.url, title: previous.title, constraints })); + this.store.saveProfile(id, profiles.build({ + id, url: previous.url, + title: parts.title !== undefined ? parts.title : previous.title, + constraints: parts.constraints !== undefined ? parts.constraints : profiles.constraintsOf(previous), + guides: parts.guides !== undefined ? parts.guides : profiles.guidesOf(previous) + })); + } + + /** A new title for a profile (its name follows it), back to the profile's page. */ + profileRename(req, res) { + const previous = req.profile; + const checked = profiles.checkInput({ title: req.body?.title, constraints: [] }, null); + if (checked.problems.length) { + return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(checked.problems.join('; ')), 400); + } + this.saveProfileParts(previous, { title: checked.title }); + this.log.info(`IPS module: clinical profile ${previous.id} renamed '${checked.title}'`); + res.redirect(`${req.baseUrl}/StructureDefinition/${previous.id}`); + } + + /** The guide a request names (:n, its place in the profile's guided input), or -1. */ + guideIndex(req, guides) { + const n = /^\d{1,4}$/.test(req.params.n || '') ? parseInt(req.params.n, 10) : -1; + return n >= 0 && n < guides.length ? n : -1; + } + + /** + * Add an input guide to a profile ({guide}: section, questions, resource, code), or replace + * one (its questions keep their linkIds). 201/200 with {index}, 404 when there is no such + * guide, 422 with {problems}. + */ + guideSave(req, res, n) { + const previous = req.profile; + const guides = profiles.guidesOf(previous); + const at = n === null ? guides.length : this.guideIndex(req, guides); + if (at < 0) { + return res.status(404).json({ problems: [`The profile has no input guide ${n}`] }); + } + const guide = req.body?.guide; + // the guide by itself first, so what is wrong is said of it, not of a number in the list + const alone = profiles.checkGuides([guide], previous); + if (alone.problems.length) { + return res.status(422).json({ problems: alone.problems.map(p => p.replace(/^Input guide 1/, 'The guide')) }); + } + guides.splice(at, n === null ? 0 : 1, guide); + const checked = profiles.checkGuides(guides, previous); + if (checked.problems.length) { + return res.status(422).json({ problems: checked.problems }); + } + this.saveProfileParts(previous, { guides: checked.guides }); + this.log.info(`IPS module: clinical profile ${previous.id}: input guide ${at + 1} ${n === null ? 'added' : 'saved'}`); + res.status(n === null ? 201 : 200).json({ index: at }); + } + + /** Delete an input guide (its questions go from the Questionnaire), back to the profile's page. */ + guideDelete(req, res) { + const previous = req.profile; + const guides = profiles.guidesOf(previous); + const at = this.guideIndex(req, guides); + if (at < 0) { + return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(`The profile has no input guide ${req.params.n}`), 404); + } + guides.splice(at, 1); + this.saveProfileParts(previous, { guides }); + this.log.info(`IPS module: clinical profile ${previous.id}: input guide ${at + 1} deleted`); + res.redirect(`${req.baseUrl}/StructureDefinition/${previous.id}#guided-input`); + } + + /** Move an input guide up or down (direction) past the next one in its section, back to the profile's page. */ + guideMove(req, res) { + const previous = req.profile; + const guides = profiles.guidesOf(previous); + const at = this.guideIndex(req, guides); + if (at < 0) { + return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(`The profile has no input guide ${req.params.n}`), 404); + } + const key = (g) => `${g.section?.system}|${g.section?.code}`; + const same = guides.map((g, i) => i).filter(i => key(guides[i]) === key(guides[at])); + const k = same.indexOf(at); + const other = req.body?.direction === 'up' ? same[k - 1] : same[k + 1]; + if (other !== undefined) { + [guides[at], guides[other]] = [guides[other], guides[at]]; + this.saveProfileParts(previous, { guides }); + } + res.redirect(`${req.baseUrl}/StructureDefinition/${previous.id}#guided-input`); } // ---- the editor ---- diff --git a/ips/profile-editor.js b/ips/profile-editor.js index 547149f3..364d5b6e 100644 --- a/ips/profile-editor.js +++ b/ips/profile-editor.js @@ -12,20 +12,19 @@ * (Bundle.section(...)[.entry(...) or .entryIn(valueSet...)].exists(), a row of the first * table), rules about resources (Bundle.resources(...) or Bundle.resourcesIn(valueSet...), and * the rest: a row of the second - type, system, code or value set, the rest), and - * other rules (FHIRPath). A row's expression is made from it. Saving posts the title and the - * constraints (key, description, expression); the server checks them, and keeps the keys. - * With cfg.mode 'rows' it is the profile's own page instead: the rows are the page's tables, - * and one at a time is added or edited, in a dialog, and saved by itself. + * other rules (FHIRPath). A row's expression is made from it. The rows are the page's tables: + * one at a time is added or edited, in a dialog, and saved by itself (the server checks it, and + * keeps the keys). So is guided input (cfg.profile.guides): a guide at a time - its section, its + * questions, and the resource and code - in the same dialog, saved to cfg.urls.guide. */ (function () { 'use strict'; var cfg = window.IPS_PROFILE; - var root = document.getElementById('ips-profile-editor'); var LOINC = cfg.sectionSystem; var dirty = false; var saving = false; - // what to draw again when a row's fields change shape: the whole editor, or the row being edited - var redraw = function () { draw(); }; + // what to draw again when a row's fields change shape: the dialog (rowsMode sets it) + var redraw = function () {}; function el(tag, attrs, children) { var e = document.createElement(tag); @@ -37,12 +36,10 @@ } function changed() { dirty = true; } - // ---- the two shapes (as ips/profiles.js has them) ---- + // ---- writing the rules (the shapes are ips/profiles.js's: the page gives each rule's) ---- var STR = "'((?:[^'\\\\]|\\\\.)*)'"; - var ARGS = '\\s*' + STR + '\\s*,\\s*' + STR + "\\s*(?:,\\s*(\\d{1,6})\\s*,\\s*(?:(\\d{1,6})|'\\*')\\s*)?"; - var CARD = "(?:,\\s*(\\d{1,6})\\s*,\\s*(?:(\\d{1,6})|'\\*')\\s*)?"; - var SHAPE_RE = new RegExp('^\\s*Bundle\\s*\\.\\s*section\\s*\\(' + ARGS + '\\)\\s*(?:\\.\\s*(?:entry\\s*\\(' + ARGS + '\\)|entryIn\\s*\\(\\s*' + STR + '\\s*' + CARD + '\\))\\s*)?\\.\\s*exists\\s*\\(\\s*\\)\\s*$'); + var SECTION_CHECKS = ['isKnown', 'hasData', 'sameSubject']; var CANONICAL_RE = /^[a-z][a-z0-9+.-]*:[^\s|]{1,250}(\|[^\s|]{1,64})?$/i; // the system chosen for an entry or resources when they are matched by value set, not code var VS = '#vs'; @@ -53,21 +50,6 @@ }); } function quote(s) { return "'" + String(s).replace(/\\/g, '\\\\').replace(/'/g, "\\'") + "'"; } - function card(min, max, hasCard) { return { min: hasCard ? parseInt(min, 10) : null, max: hasCard ? (max === undefined ? '*' : parseInt(max, 10)) : null }; } - function part(system, code, min, max, hasCard) { - var c = card(min, max, hasCard); - return { system: unquote(system), code: unquote(code), min: c.min, max: c.max }; - } - function parseShape(expression) { - var m = SHAPE_RE.exec(expression || ''); - if (!m) { return null; } - var entry = null; - if (m[5] !== undefined) { entry = part(m[5], m[6], m[7], m[8], m[7] !== undefined); } else if (m[9] !== undefined) { - var c = card(m[10], m[11], m[10] !== undefined); - entry = { valueSet: unquote(m[9]), min: c.min, max: c.max }; - } - return { section: part(m[1], m[2], m[3], m[4], m[3] !== undefined), entry: entry }; - } function cardText(p) { return p.min === null || p.min === undefined ? '' : p.min + '..' + p.max; } function parseCard(text) { if (!text || !text.trim()) { return { min: null, max: null }; } @@ -79,16 +61,6 @@ } function cardArgs(c) { return c.min !== null ? ', ' + c.min + ', ' + (c.max === '*' ? "'*'" : c.max) : ''; } function args(system, code, c) { return quote(system) + ', ' + quote(code) + cardArgs(c); } - var TYPE = "\\s*(?:,\\s*'([A-Z][A-Za-z]{1,63})'\\s*)?"; - var REST = '\\s*(\\.\\s*\\S[\\s\\S]*?)\\s*$'; - var RSHAPE_RE = new RegExp('^\\s*Bundle\\s*\\.\\s*resources\\s*\\(\\s*' + STR + '\\s*,\\s*' + STR + TYPE + '\\)' + REST); - var RSHAPE_IN_RE = new RegExp('^\\s*Bundle\\s*\\.\\s*resourcesIn\\s*\\(\\s*' + STR + TYPE + '\\)' + REST); - function parseResourceShape(expression) { - var m = RSHAPE_RE.exec(expression || ''); - if (m) { return { type: m[3] || null, system: unquote(m[1]), code: unquote(m[2]), rest: m[4] }; } - m = RSHAPE_IN_RE.exec(expression || ''); - return m ? { type: m[2] || null, valueSet: unquote(m[1]), rest: m[3] } : null; - } // ---- the rows: mode 'section' (the first table), 'resource' (the second) or 'text' ---- @@ -96,7 +68,7 @@ var shape = c.shape || null; var rshape = c.rshape || null; var r = { key: c.key || null, human: c.human || '', expression: c.expression || '', mode: shape ? 'section' : (rshape ? 'resource' : 'text') }; - tableFields(r, shape || { section: { system: LOINC, code: '', min: null, max: null }, entry: null }); + tableFields(r, shape || { section: { system: LOINC, code: '', checks: [] }, entry: null }); resourceFields(r, rshape || { type: null, system: cfg.systems[0].url, code: '', rest: '.exists()' }); return r; } @@ -135,7 +107,8 @@ var e = shape.entry; r.secSystem = shape.section.system; r.secCode = shape.section.code; - r.secCard = cardText(shape.section); + r.secChecks = {}; + SECTION_CHECKS.forEach(function (c) { r.secChecks[c] = (shape.section.checks || []).indexOf(c) >= 0; }); r.secDisplay = ''; r.entSystem = !e ? '' : (e.valueSet !== undefined ? VS : e.system); r.entCode = e && e.valueSet === undefined ? e.code : ''; @@ -147,12 +120,10 @@ /** The row's expression, from its table, or null with what is wrong. */ function tableExpression(r) { var problems = []; - var sc = parseCard(r.secCard); var ec = parseCard(r.entCard); var byVs = r.entSystem === VS; if (!r.secSystem.trim()) { problems.push('secSystem'); } if (!r.secCode.trim()) { problems.push('secCode'); } - if (!sc) { problems.push('secCard'); } if (r.entSystem.trim() || r.entCode.trim() || r.entCard.trim()) { if (byVs) { if (!CANONICAL_RE.test(r.entVs.trim())) { problems.push('entVs'); } @@ -163,13 +134,15 @@ if (!ec) { problems.push('entCard'); } } if (problems.length) { return { expression: null, problems: problems }; } - var x = 'Bundle.section(' + args(r.secSystem.trim(), r.secCode.trim(), sc) + ')'; - if (byVs) { x += '.entryIn(' + quote(r.entVs.trim()) + cardArgs(ec) + ')'; } else if (r.entSystem.trim()) { x += '.entry(' + args(r.entSystem.trim(), r.entCode.trim(), ec) + ')'; } - return { expression: x + '.exists()', problems: [] }; + // one check on its own is the rule; more than one, or any with entries, go in a where() + var checks = SECTION_CHECKS.filter(function (c) { return r.secChecks[c]; }); + var x = 'Bundle.section(' + quote(r.secSystem.trim()) + ', ' + quote(r.secCode.trim()) + ')'; + var entry = byVs ? '.entryIn(' + quote(r.entVs.trim()) + cardArgs(ec) + ')' : (r.entSystem.trim() ? '.entry(' + args(r.entSystem.trim(), r.entCode.trim(), ec) + ')' : ''); + if (!entry && checks.length === 1) { return { expression: x + '.' + checks[0] + '()', problems: [] }; } + if (checks.length) { x += '.where(' + checks.map(function (c) { return c + '()'; }).join(' and ') + ')'; } + return { expression: x + entry + '.exists()', problems: [] }; } - var state = { title: cfg.profile.title || '', rows: (cfg.profile.constraints || []).map(rowFrom) }; - // ---- a code, looked up in a system ---- function codeInput(r, codeField, displayField, systemOf, onChange) { @@ -308,6 +281,20 @@ return wrap; } + // what the section must be: asked/known (isKnown()), with supporting entries (hasData()), + // about the document's patient (sameSubject()) - checkboxes in a row + var CHECK_LABELS = { isKnown: 'must be asked/known', hasData: 'must have supporting entries', sameSubject: 'about the same Patient' }; + function sectionChecks(r, onChange) { + var row = el('div', { class: 'ips-pf-checks' }); + SECTION_CHECKS.forEach(function (c) { + var box = el('input', { type: 'checkbox' }); + box.checked = !!r.secChecks[c]; + box.addEventListener('change', function () { r.secChecks[c] = box.checked; changed(); onChange(); }); + row.appendChild(el('label', { class: 'ips-pf-check', title: c + '()' }, [box, ' ' + CHECK_LABELS[c]])); + }); + return row; + } + function cardInput(r, field, onChange) { var input = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'any', title: 'blank for any number, or min..max (1..1, 1..*)' }); input.value = r[field]; @@ -319,7 +306,9 @@ function sectionCell(r, onChange) { var cell = el('div'); var select = el('select', { class: 'form-control ips-ed-input' }); - cfg.sections.forEach(function (s) { select.appendChild(el('option', { value: s.code, text: 'Section: ' + s.title })); }); + // by title, then another code last + cfg.sections.slice().sort(function (a, b) { return a.title.localeCompare(b.title); }) + .forEach(function (s) { select.appendChild(el('option', { value: s.code, text: 'Section: ' + s.title })); }); select.appendChild(el('option', { value: '', text: 'Another code...' })); var isIps = r.secSystem === LOINC && cfg.sections.some(function (s) { return s.code === r.secCode; }); if (!r.secCode) { r.secSystem = LOINC; r.secCode = cfg.sections[0].code; isIps = true; } @@ -428,157 +417,6 @@ return cell; } - function drawRow(r, n) { - var box = el('div', { class: 'ips-pf-row' }); - var human = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'What is expected (shown to people)' }); - human.value = r.human; - human.addEventListener('input', function () { r.human = human.value; changed(); }); - var toggle = el('a', { href: '#', class: 'ips-small', text: r.mode === 'text' ? 'Edit as table' : 'Edit as FHIRPath' }); - toggle.addEventListener('click', function (e) { - e.preventDefault(); - if (r.mode !== 'text') { - var t = rowExpression(r); - if (t.expression) { r.expression = t.expression; } - r.mode = 'text'; - } else { - var shape = parseShape(r.expression); - var rshape = shape ? null : parseResourceShape(r.expression); - if (!shape && !rshape) { - window.alert('This rule is not one the tables can show: Bundle.section(...).exists(), Bundle.section(...).entry(...).exists() or .entryIn(...).exists(), or Bundle.resources(...) or Bundle.resourcesIn(...) and the rest of the rule'); - return; - } - if (shape) { tableFields(r, shape); r.mode = 'section'; } else { resourceFields(r, rshape); r.mode = 'resource'; } - } - changed(); - draw(); - }); - var remove = el('button', { type: 'button', class: 'btn btn-default ips-btn', style: 'font-size: 85%; padding: 1px 8px', text: 'Remove' }); - remove.addEventListener('click', function () { state.rows.splice(state.rows.indexOf(r), 1); changed(); draw(); }); - box.appendChild(el('div', { class: 'ips-pf-head' }, [el('b', { text: String(n) + '.' }), human, toggle, remove])); - if (r.mode === 'text') { - var text = el('textarea', { class: 'form-control ips-ed-input', rows: 2, placeholder: 'A FHIRPath expression on the document (the Bundle), true when it meets the expectation', style: 'font-family: monospace; width: 100%' }); - text.value = r.expression; - text.addEventListener('input', function () { r.expression = text.value; changed(); }); - box.appendChild(text); - return box; - } - var exprLine = el('div', { class: 'ips-pf-expr' }); - var fields = {}; - var update = function () { - var t = rowExpression(r); - exprLine.textContent = t.expression || '(incomplete)'; - Object.keys(fields).forEach(function (k) { fields[k].classList.toggle('ips-pf-bad', t.problems.indexOf(k) >= 0); }); - }; - var grid; - if (r.mode === 'section') { - var sec = sectionCell(r, update); - var ent = entryCell(r, update); - fields.secCard = cardInput(r, 'secCard', update); - fields.entCard = cardInput(r, 'entCard', update); - if (ent.code) { fields.entCode = ent.code.input; } - if (ent.vs) { fields.entVs = ent.vs.input; } - grid = el('table', { class: 'ips-pf-grid' }, [ - el('tr', {}, [el('th', { text: 'Section' }), el('th', { text: 'Cardinality' }), el('th', { text: 'Entries' }), el('th', { text: 'Cardinality' })]), - el('tr', {}, [el('td', {}, [sec]), el('td', { class: 'ips-pf-card' }, [fields.secCard]), el('td', {}, [ent]), el('td', { class: 'ips-pf-card' }, [fields.entCard])]) - ]); - } else { - var type = typeCell(r, update); - var system = systemCell(r, update); - var byVs = r.resSystem === VS; - var code = byVs ? vsInput(r, 'resVs', 'resVsTitle', update) : codeInput(r, 'resCode', 'resDisplay', function () { return r.resSystem; }, update); - var rest = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: '.exists()', style: 'font-family: monospace; width: 100%', title: 'The rest of the rule: FHIRPath on the resources found, starting with a dot' }); - rest.value = r.resRest; - rest.addEventListener('input', function () { r.resRest = rest.value; changed(); update(); }); - fields.resType = type.other; - fields.resSystem = system.url; - fields[byVs ? 'resVs' : 'resCode'] = code.input; - fields.resRest = rest; - grid = el('table', { class: 'ips-pf-grid' }, [ - el('tr', {}, [el('th', { text: 'Type' }), el('th', { text: 'System' }), el('th', { text: byVs ? 'Value set' : 'Code' }), el('th', { text: 'Rule' })]), - el('tr', {}, [el('td', { style: 'width: 16%' }, [type]), el('td', { style: 'width: 18%' }, [system]), el('td', { style: byVs ? 'width: 34%' : 'width: 22%' }, [code]), el('td', {}, [rest])]) - ]); - } - box.appendChild(grid); - box.appendChild(exprLine); - update(); - return box; - } - - var ADD_LABELS = { section: 'Add a required section/entry', resource: 'Add a rule about resources', text: 'Add another rule' }; - var MODE_OF_PART = { section: 'section', resource: 'resource', other: 'text' }; - var messages = el('div'); - - /** The rows as the page shows them: the parts in order. */ - function ordered() { - var out = []; - cfg.parts.forEach(function (p) { state.rows.forEach(function (r) { if (r.mode === MODE_OF_PART[p[0]]) { out.push(r); } }); }); - return out; - } - - function draw() { - root.innerHTML = ''; - var title = el('input', { type: 'text', class: 'form-control', placeholder: 'The profile\'s title, e.g. Cardiology referral', style: 'font-size: 110%; font-weight: bold' }); - title.value = state.title; - title.addEventListener('input', function () { state.title = title.value; changed(); }); - root.appendChild(el('div', { class: 'ips-banner' }, [el('label', { class: 'ips-small', text: 'Title' }), title])); - var n = 0; - cfg.parts.forEach(function (p) { - var mode = MODE_OF_PART[p[0]]; - root.appendChild(el('h4', { text: p[1] })); - var these = state.rows.filter(function (r) { return r.mode === mode; }); - if (!these.length) { root.appendChild(el('p', { class: 'ips-small', text: 'None.' })); } - these.forEach(function (r) { root.appendChild(drawRow(r, ++n)); }); - root.appendChild(el('div', { class: 'ips-actions-line' }, [el('button', { type: 'button', class: 'btn btn-default', text: ADD_LABELS[mode], onclick: function () { - var r = rowFrom({}); - r.mode = mode; - state.rows.push(r); - changed(); - draw(); - } })])); - }); - root.appendChild(messages); - root.appendChild(el('div', { class: 'ips-actions-line' }, [ - el('button', { type: 'button', class: 'btn btn-primary', text: 'Save', onclick: save }), ' ', - el('a', { class: 'btn btn-default', href: cfg.urls.back, text: 'Cancel' }) - ])); - } - - function show(problems, kind) { - messages.innerHTML = ''; - if (!problems.length) { return; } - var box = el('div', { class: 'alert alert-' + (kind || 'danger') }); - if (problems.length === 1) { box.textContent = problems[0]; } else { - box.appendChild(el('ul', { style: 'margin: 0' }, problems.map(function (p) { return el('li', { text: p }); }))); - } - messages.appendChild(box); - } - - function save() { - if (saving) { return; } - var problems = []; - // in the page's order, so the numbers in the server's messages are the page's - var constraints = ordered().map(function (r, i) { - var t = rowExpression(r); - if (!t.expression && r.mode !== 'text') { problems.push('Rule ' + (i + 1) + ' is incomplete (the fields in red)'); } - return { key: r.key, human: r.human, expression: t.expression || '' }; - }); - if (!state.title.trim()) { problems.unshift('The profile needs a title'); } - if (problems.length) { show(problems); return; } - saving = true; - show(['Saving...'], 'info'); - fetch(cfg.urls.save, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, - body: JSON.stringify({ title: state.title, constraints: constraints, _csrf: cfg.csrf }) }) - .then(function (res) { - return res.json().then(function (j) { return { ok: res.ok, j: j }; }, function () { return { ok: false, j: { problems: ['The server answered ' + res.status + (res.status === 403 ? ' (has your session expired? reload the page)' : '')] } }; }); - }) - .then(function (a) { - saving = false; - if (a.ok) { dirty = false; location.href = a.j.url; return; } - show(a.j.problems || ['The profile was not saved']); - }) - .catch(function (e) { saving = false; show(['The profile was not saved: ' + e.message]); }); - } - // ---- the profile's page: a rule at a time, added or edited in a dialog ---- // what must be true of the resources a rule is about: the rest of the rule, by kind @@ -651,6 +489,117 @@ return { expression: t.rest ? e.expression : null, problems: t.problems.concat(e.problems.filter(function (p) { return p !== 'resRest'; })) }; } + // ---- guided input: a guide (its section, questions, resource and code) as the dialog edits it ---- + + var UCUM = 'http://unitsofmeasure.org'; + var TYPE_LABELS = { display: 'Text to show', boolean: 'Yes / no', quantity: 'Quantity', date: 'Date', choice: 'Choice' }; + + function copyCoding(c) { return c ? { system: c.system || '', code: c.code || '', display: c.display || '' } : { system: '', code: '', display: '' }; } + function guideRow(g, index) { + g = g || {}; + var r = { mode: 'guide', index: index, key: index === null ? null : 'guide' }; + var s = g.section || {}; + r.secSystem = s.system || LOINC; + r.secCode = s.code || ''; + r.secDisplay = s.display || ''; + r.secChecks = {}; + r.questions = (g.questions || []).map(function (q) { + return { linkId: q.linkId || null, text: q.text || '', type: q.type || 'boolean', definition: q.definition || '', + answers: (q.answers || []).map(copyCoding), units: (q.units || []).map(copyCoding) }; + }); + if (!r.questions.length) { r.questions.push({ linkId: null, text: '', type: 'boolean', definition: '', answers: [], units: [] }); } + r.resource = g.resource || ''; + r.code = copyCoding(g.code); + return r; + } + function codingOut(c) { + var out = { system: (c.system || '').trim(), code: (c.code || '').trim() }; + if (c.display) { out.display = c.display; } + return out; + } + /** What the server is sent for a guide. */ + function guidePayload(r) { + var section = codingOut({ system: r.secSystem, code: r.secCode, display: r.secDisplay }); + return { + section: section, + questions: r.questions.map(function (q) { + return { linkId: q.linkId, text: q.text, type: q.type, definition: q.definition.trim(), + answers: q.type === 'choice' ? q.answers.map(codingOut) : [], units: q.type === 'quantity' ? q.units.map(codingOut) : [] }; + }), + resource: r.resource || null, + code: r.resource && r.code.code.trim() ? codingOut(r.code) : null + }; + } + /** A Coding: a system (a named one, or another by URL) and a code, looked up in it. */ + function codingPicker(c, onChange, defaultSystem) { + if (!c.system) { c.system = defaultSystem || cfg.systems[0].url; } + var cell = el('div', { class: 'ips-pf-coding' }); + var select = el('select', { class: 'form-control ips-ed-input' }); + cfg.systems.forEach(function (sy) { select.appendChild(el('option', { value: sy.url, text: sy.name })); }); + select.appendChild(el('option', { value: '*', text: 'Another system...' })); + var named = cfg.systems.some(function (sy) { return sy.url === c.system; }); + select.value = named ? c.system : '*'; + var url = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'code system URL', 'aria-label': 'Code system URL' }); + url.value = named ? '' : c.system; + url.hidden = named; + url.addEventListener('input', function () { c.system = url.value.trim(); changed(); onChange(); }); + select.addEventListener('change', function () { + url.hidden = select.value !== '*'; + c.system = select.value === '*' ? url.value.trim() : select.value; + changed(); + onChange(); + }); + cell.appendChild(el('div', { class: 'ips-pf-pair' }, [select, url])); + cell.appendChild(codeInput(c, 'code', 'display', function () { return c.system; }, onChange)); + return cell; + } + function smallButton(text, title, onclick) { + return el('button', { type: 'button', class: 'btn btn-default ips-btn', title: title, 'aria-label': title, text: text, onclick: onclick }); + } + /** A list of Codings: each with a Remove button, and an Add button. */ + function codingList(list, label, onChange, defaultSystem) { + var box = el('div'); + list.forEach(function (c, i) { + box.appendChild(el('div', { class: 'ips-pf-list-row' }, [codingPicker(c, onChange, defaultSystem), + smallButton('×', 'Remove this ' + label, function () { list.splice(i, 1); changed(); redraw(); })])); + }); + box.appendChild(smallButton('Add ' + (label === 'answer' ? 'an ' : 'a ') + label, 'Add ' + (label === 'answer' ? 'an ' : 'a ') + label, function () { + list.push({ system: '', code: '', display: '' }); + changed(); + redraw(); + })); + return box; + } + /** A question: its text, type and definition, and its answers (a choice) or units (a quantity). */ + function questionBox(r, q, i) { + var box = el('div', { class: 'ips-pf-question' }); + var text = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'The question, as people will read it', 'aria-label': 'Question ' + (i + 1) }); + text.value = q.text; + text.addEventListener('input', function () { q.text = text.value; changed(); }); + var type = el('select', { class: 'form-control ips-ed-input', style: 'flex: none; width: 9em', 'aria-label': 'Question ' + (i + 1) + ' type' }); + (cfg.questionTypes || []).forEach(function (t) { type.appendChild(el('option', { value: t, text: TYPE_LABELS[t] || t })); }); + type.value = q.type; + type.addEventListener('change', function () { q.type = type.value; changed(); redraw(); }); + var move = function (d) { return function () { var t = r.questions[i]; r.questions[i] = r.questions[i + d]; r.questions[i + d] = t; changed(); redraw(); }; }; + var head = [text, type]; + if (i > 0) { head.push(smallButton('↑', 'Move up', move(-1))); } + if (i < r.questions.length - 1) { head.push(smallButton('↓', 'Move down', move(1))); } + if (r.questions.length > 1) { head.push(smallButton('×', 'Delete this question', function () { r.questions.splice(i, 1); changed(); redraw(); })); } + box.appendChild(el('div', { class: 'ips-pf-qhead' }, head)); + var def = el('input', { type: 'text', class: 'form-control ips-ed-input', placeholder: 'definition (optional): a path in a resource, e.g. Condition.onset[x]', 'aria-label': 'Question ' + (i + 1) + ' definition', style: 'margin-top: 4px; font-family: monospace' }); + def.value = q.definition; + def.addEventListener('input', function () { q.definition = def.value; changed(); }); + box.appendChild(def); + if (q.type === 'choice') { + box.appendChild(el('div', { class: 'ips-pf-hint', text: 'The answers to choose from:' })); + box.appendChild(codingList(q.answers, 'answer', function () {})); + } else if (q.type === 'quantity') { + box.appendChild(el('div', { class: 'ips-pf-hint', text: 'The units it can be given in (optional):' })); + box.appendChild(codingList(q.units, 'unit', function () {}, UCUM)); + } + return box; + } + function rowsMode() { var MODE = { section: 'section', resource: 'resource', other: 'text' }; var TITLES = { section: 'a required section or entry', resource: 'a rule about resources', text: 'a rule' }; @@ -709,6 +658,7 @@ var e = editing; var r = e.r; dialog.innerHTML = ''; + if (r.mode === 'guide') { drawGuideDialog(e, r); return; } var fields = {}; var exprLine = el('div', { class: 'ips-pf-expr' }); var update = function () { @@ -723,7 +673,7 @@ body.appendChild(field('Expectation', [human], 'What is expected, as people will read it.')); if (r.mode === 'section') { - body.appendChild(field('Section', [sectionCell(r, update), howMany(r, 'secCard', update, fields)])); + body.appendChild(field('Section', [sectionCell(r, update), sectionChecks(r, update)])); var ent = entryCell(r, update); if (ent.code) { fields.entCode = ent.code.input; } if (ent.vs) { fields.entVs = ent.vs.input; } @@ -795,6 +745,59 @@ if (!e.focused) { e.focused = true; human.focus(); } } + /** the dialog for a guide: its section, its questions, and the resource and code */ + function drawGuideDialog(e, r) { + var body = el('div', { class: 'ips-pf-dialog-body' }); + body.appendChild(field('Section', [sectionCell(r, function () {})], 'The section the questions are about.')); + var qs = el('div'); + r.questions.forEach(function (q, i) { qs.appendChild(questionBox(r, q, i)); }); + qs.appendChild(smallButton('Add a question', 'Add a question', function () { + r.questions.push({ linkId: null, text: '', type: 'boolean', definition: '', answers: [], units: [] }); + changed(); + redraw(); + })); + body.appendChild(field('Questions', [qs], 'In the order they are asked. The definition, if given, is the element of the resource the answer goes in.')); + var res = el('select', { class: 'form-control ips-ed-input', 'aria-label': 'Resource' }, [el('option', { value: '', text: '(none)' })]); + (cfg.guideResources || []).forEach(function (x) { res.appendChild(el('option', { value: x.code, text: x.label })); }); + res.value = r.resource; + res.addEventListener('change', function () { r.resource = res.value; changed(); redraw(); }); + body.appendChild(field('Resource', [res], 'The resource the answers make, if any.')); + if (r.resource) { + body.appendChild(field('Code', [codingPicker(r.code, function () {})], 'The resource\'s code (optional).')); + } + body.appendChild(e.msg); + var save = el('button', { type: 'button', class: 'btn btn-primary', text: 'Save', onclick: function () { saveGuide(); } }); + var cancel = el('button', { type: 'button', class: 'btn btn-default', text: 'Cancel', onclick: function () { stop(false); } }); + e.save = save; + dialog.appendChild(el('div', { class: 'ips-pf-dialog-head' }, [ + el('h4', { id: 'ips-pf-dialog-title', text: (r.index === null ? 'Add' : 'Edit') + ' guided input' }), + el('button', { type: 'button', class: 'ips-pf-dialog-x', 'aria-label': 'Close', text: '\u00d7', onclick: function () { stop(false); } }) + ])); + dialog.appendChild(body); + dialog.appendChild(el('div', { class: 'ips-pf-dialog-foot' }, [cancel, ' ', save])); + } + + function saveGuide() { + var e = editing; + if (!e || saving) { return; } + saving = true; + e.save.disabled = true; + showIn(e.msg, ['Saving...'], 'info'); + var url = cfg.urls.guide + (e.r.index === null ? '' : '/' + e.r.index); + fetch(url, { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify({ guide: guidePayload(e.r), _csrf: cfg.csrf }) }) + .then(function (res) { + return res.json().then(function (j) { return { ok: res.ok, j: j }; }, function () { return { ok: false, j: { problems: ['The server answered ' + res.status + (res.status === 403 ? ' (has your session expired? reload the page)' : '')] } }; }); + }) + .then(function (a) { + saving = false; + if (a.ok) { stop(true); location.hash = 'guided-input'; location.reload(); return; } + e.save.disabled = false; + showIn(e.msg, a.j.problems || ['The guided input was not saved']); + }) + .catch(function (x) { saving = false; e.save.disabled = false; showIn(e.msg, ['The guided input was not saved: ' + x.message]); }); + } + function start(r) { if (editing) { return; } if (r.mode === 'resource') { ruleFields(r); } @@ -843,6 +846,16 @@ if (c) { start(rowFrom(c)); } }); }); + Array.prototype.forEach.call(document.querySelectorAll('.ips-pf-edit-guide'), function (b) { + b.addEventListener('click', function () { + var n = parseInt(b.closest('td').getAttribute('data-guide'), 10); + var g = (cfg.profile.guides || [])[n]; + if (g) { start(guideRow(g, n)); } + }); + }); + Array.prototype.forEach.call(document.querySelectorAll('.ips-pf-add-guide'), function (b) { + b.addEventListener('click', function () { start(guideRow(null, null)); }); + }); Array.prototype.forEach.call(document.querySelectorAll('.ips-pf-add'), function (b) { b.addEventListener('click', function () { var r = rowFrom({}); @@ -853,5 +866,5 @@ } window.addEventListener('beforeunload', function (e) { if (dirty) { e.preventDefault(); e.returnValue = ''; } }); - if (cfg.mode === 'rows') { rowsMode(); } else { draw(); } + rowsMode(); })(); diff --git a/ips/profiles.js b/ips/profiles.js index d1afdb58..d4779188 100644 --- a/ips/profiles.js +++ b/ips/profiles.js @@ -60,8 +60,11 @@ const SYSTEMS = [ { url: 'http://unitsofmeasure.org', name: 'UCUM' } ]; -/** The IPS sections, for the editor's shortcuts and the read-only view. */ -const IPS_SECTIONS = SECTIONS.map(s => ({ code: s.code, title: s.title })); +/** + * The IPS sections, for the editor's shortcuts and the read-only view: the general editor's, and + * the Patient Story (which that editor doesn't make). + */ +const IPS_SECTIONS = [...SECTIONS.map(s => ({ code: s.code, title: s.title })), { code: '81338-6', title: 'Patient Story' }]; function isObject(v) { return v !== null && typeof v === 'object' && !Array.isArray(v); @@ -72,8 +75,21 @@ function isObject(v) { const STR = "'((?:[^'\\\\]|\\\\.)*)'"; const ARGS = `\\s*${STR}\\s*,\\s*${STR}\\s*(?:,\\s*(\\d{1,6})\\s*,\\s*(?:(\\d{1,6})|'\\*')\\s*)?`; const CARD = `(?:,\\s*(\\d{1,6})\\s*,\\s*(?:(\\d{1,6})|'\\*')\\s*)?`; -// the entry part: entry(system, code [, min, max]) or entryIn(valueSet [, min, max]) -const SHAPE_RE = new RegExp(`^\\s*Bundle\\s*\\.\\s*section\\s*\\(${ARGS}\\)\\s*(?:\\.\\s*(?:entry\\s*\\(${ARGS}\\)|entryIn\\s*\\(\\s*${STR}\\s*${CARD}\\))\\s*)?\\.\\s*exists\\s*\\(\\s*\\)\\s*$`); +// a required section (and entries) rule is Bundle.section(system, code) - no bounds: a section +// with bounds is a rule of its own (other) - then the section's checks, then the entry part: +// Bundle.section(s, c).exists() the section is there +// Bundle.section(s, c).isKnown() one check (no entry part) +// Bundle.section(s, c).where(isKnown() and hasData()).exists() more than one +// Bundle.section(s, c)[.where(checks)].entry(system, code [, min, max]).exists() +// Bundle.section(s, c)[.where(checks)].entryIn(valueSet [, min, max]).exists() +const SECTION_HEAD_RE = new RegExp(`^\\s*Bundle\\s*\\.\\s*section\\s*\\(\\s*${STR}\\s*,\\s*${STR}\\s*\\)`); +// the section checks, in the order they are written +const SECTION_CHECKS = ['isKnown', 'hasData', 'sameSubject']; +const CHECK = '(isKnown|hasData|sameSubject)\\s*\\(\\s*\\)'; +const ONE_CHECK_RE = new RegExp(`^\\s*\\.\\s*${CHECK}\\s*$`); +const WHERE_RE = new RegExp(`^\\s*\\.\\s*where\\s*\\(\\s*(${CHECK.replace(/\(isKnown/, '(?:isKnown')}(?:\\s+and\\s+${CHECK.replace(/\(isKnown/, '(?:isKnown')})*)\\s*\\)`); +const ENTRY_RE = new RegExp(`^\\s*\\.\\s*(?:entry\\s*\\(${ARGS}\\)|entryIn\\s*\\(\\s*${STR}\\s*${CARD}\\))`); +const EXISTS_RE = /^\s*\.\s*exists\s*\(\s*\)\s*$/; // a value set's canonical, as entryIn() and resourcesIn() take it const CANONICAL_RE = /^[a-z][a-z0-9+.-]*:[^\s|]{1,250}(\|[^\s|]{1,64})?$/i; @@ -95,36 +111,65 @@ function part(system, code, min, max, hasCard) { return { system: unquote(system), code: unquote(code), ...card(min, max, hasCard) }; } +/** The checks named in a where(): in their order, or null when one is named twice. */ +function checksIn(list) { + const names = list.split(/\s+and\s+/).map(x => x.replace(/\s*\(\s*\)\s*$/, '').trim()); + return new Set(names).size === names.length ? SECTION_CHECKS.filter(c => names.includes(c)) : null; +} + /** * The parts of an expression in one of the two shapes, or null. - * @returns {{section: {system, code, min, max}, entry: {system, code, min, max}|{valueSet, min, max}|null}|null} - * min and max are null for no bounds; max is a number or '*'; an entry has a system and - * code, or a value set + * @returns {{section: {system, code, checks: string[]}, entry: {system, code, min, max}|{valueSet, min, max}|null}|null} + * checks are isKnown, hasData, sameSubject (in that order); an entry's min and max are null + * for no bounds, max is a number or '*'; an entry has a system and code, or a value set */ function parseShape(expression) { if (typeof expression !== 'string' || expression.length > MAX_EXPRESSION) { return null; } - const m = SHAPE_RE.exec(expression); - if (!m) { + const head = SECTION_HEAD_RE.exec(expression); + if (!head) { return null; } - const section = part(m[1], m[2], m[3], m[4], m[3] !== undefined); - let entry = null; - if (m[5] !== undefined) { - entry = part(m[5], m[6], m[7], m[8], m[7] !== undefined); - } else if (m[9] !== undefined) { - entry = { valueSet: unquote(m[9]), ...card(m[10], m[11], m[10] !== undefined) }; - if (!CANONICAL_RE.test(entry.valueSet)) { + const section = { system: unquote(head[1]), code: unquote(head[2]), checks: [] }; + if (!section.system || !section.code) { + return null; + } + let rest = expression.substring(head[0].length); + const one = ONE_CHECK_RE.exec(rest); + if (one) { + section.checks = [one[1]]; + return { section, entry: null }; + } + const where = WHERE_RE.exec(rest); + if (where) { + const checks = checksIn(where[1]); + if (!checks) { return null; } + section.checks = checks; + rest = rest.substring(where[0].length); } - for (const p of [section, entry].filter(Boolean)) { - if ((p.valueSet === undefined && (!p.system || !p.code)) || (p.min !== null && p.max !== '*' && p.max < p.min)) { + let entry = null; + const m = ENTRY_RE.exec(rest); + if (m) { + if (m[1] !== undefined) { + entry = part(m[1], m[2], m[3], m[4], m[3] !== undefined); + if (!entry.system || !entry.code) { + return null; + } + } else { + entry = { valueSet: unquote(m[5]), ...card(m[6], m[7], m[6] !== undefined) }; + if (!CANONICAL_RE.test(entry.valueSet)) { + return null; + } + } + if (entry.min !== null && entry.max !== '*' && entry.max < entry.min) { return null; } + rest = rest.substring(m[0].length); } - return { section, entry }; + return EXISTS_RE.test(rest) ? { section, entry } : null; } const TYPE = `(?:,\\s*'([A-Z][A-Za-z]{1,63})'\\s*)?`; @@ -175,11 +220,20 @@ function args(p) { return `${quote(p.system)}, ${quote(p.code)}` + cardArgs(p); } -/** The expression for a shape. */ +/** + * The expression for a shape: one check on its own is the rule (Bundle.section(...).isKnown()); + * more than one, or any with an entry part, go in a where() before it. + */ function shapeExpression(shape) { const e = shape.entry; + const checks = SECTION_CHECKS.filter(c => (shape.section.checks || []).includes(c)); + const head = `Bundle.section(${quote(shape.section.system)}, ${quote(shape.section.code)})`; + if (!e && checks.length === 1) { + return `${head}.${checks[0]}()`; + } + const where = checks.length ? `.where(${checks.map(c => `${c}()`).join(' and ')})` : ''; const entry = !e ? '' : (e.valueSet !== undefined ? `.entryIn(${quote(e.valueSet)}${cardArgs(e)})` : `.entry(${args(e)})`); - return `Bundle.section(${args(shape.section)})` + entry + '.exists()'; + return head + where + entry + '.exists()'; } /** A cardinality as written: '' for none, else 'min..max'. */ @@ -302,12 +356,13 @@ function checkInput(input, previous = null) { /** * The StructureDefinition. - * @param {{id: string, url: string, title: string, constraints: Array, date?: string}} p + * @param {{id: string, url: string, title: string, constraints: Array, guides?: Array, date?: string}} p - guides: checked (checkGuides) */ function build(p) { return { resourceType: 'StructureDefinition', id: `profile-${p.id}`, + ...guideResources(p.guides), url: p.url, name: nameFromTitle(p.title), title: p.title, @@ -339,15 +394,15 @@ function constraintsOf(sd) { // what an uploaded StructureDefinition may have: what build() makes, and the metadata a // tool might add that is replaced anyway -const UPLOAD_KEYS = new Set(['resourceType', 'id', 'meta', 'text', 'url', 'version', 'name', 'title', 'status', 'date', 'publisher', +const UPLOAD_KEYS = new Set(['resourceType', 'id', 'meta', 'text', 'contained', 'extension', 'url', 'version', 'name', 'title', 'status', 'date', 'publisher', 'fhirVersion', 'kind', 'abstract', 'type', 'baseDefinition', 'derivation', 'differential']); const ELEMENT_KEYS = new Set(['id', 'path', 'constraint']); const CONSTRAINT_KEYS = new Set(['key', 'severity', 'human', 'expression', 'source']); /** - * An uploaded StructureDefinition, as the editor's input (title and constraints, the - * keys dropped so they are assigned afresh), or the reasons it can't be taken. - * @returns {{input: {title, constraints}|null, problems: string[]}} + * An uploaded StructureDefinition, as the editor's input (title, constraints and guided input, + * the keys and linkIds dropped so they are assigned afresh), or the reasons it can't be taken. + * @returns {{input: {title, constraints, guides}|null, problems: string[]}} */ function fromUpload(sd) { const problems = []; @@ -412,8 +467,369 @@ function fromUpload(sd) { } }); } + const guided = guidesFromUpload(sd); + problems.push(...guided.problems); const title = typeof sd.title === 'string' && sd.title.trim() ? sd.title : (typeof sd.name === 'string' ? sd.name : ''); - return { input: { title, constraints: list.map(c => (isObject(c) ? { human: c.human, expression: c.expression } : c)) }, problems }; + return { input: { title, constraints: list.map(c => (isObject(c) ? { human: c.human, expression: c.expression } : c)), guides: guided.guides }, problems }; +} + +// ---- guided input ---------------------------------------------------------------------------- +// +// A profile's guided input: input-guide extensions on the StructureDefinition, each naming +// questions in the Questionnaire it contains (#Q), the section they are about (a Coding), and +// optionally the kind of resource the answers make and its code. Their order is the extensions'. + +const INPUT_GUIDE = 'http://www.healthintersections.com.au/fhir/StructureDefinition/input-guide'; +const UNIT_OPTION = 'http://hl7.org/fhir/StructureDefinition/questionnaire-unitOption'; +const Q_ID = 'Q'; +const QUESTION_TYPES = ['display', 'boolean', 'quantity', 'date', 'choice']; +// the resources a guide can make: resource type, and the class that says how it is used +const GUIDE_RESOURCES = [ + { code: 'Condition:problem', label: 'Condition (problem)' }, + { code: 'Condition:diagnosis', label: 'Condition (diagnosis)' }, + { code: 'Observation:vitals', label: 'Observation (vital signs)' }, + { code: 'MedicationStatement', label: 'MedicationStatement' }, + { code: 'AllergyIntolerance', label: 'AllergyIntolerance' } +]; +const MAX_GUIDES = 100; +const MAX_QUESTIONS = 50; +const MAX_ANSWERS = 100; +const MAX_TEXT = 1000; +// a question's definition, as the editor has it: a path in a resource (Condition.onset[x], Observation.code.text) +const DEFINITION_RE = /^([A-Z][A-Za-z]{1,63})((?:\.[a-z][A-Za-z0-9]{0,63}(?:\[x\])?){1,8})$/; +const DEFINITION_URI_RE = /^http:\/\/hl7\.org\/fhir\/StructureDefinition\/([A-Z][A-Za-z]{1,63})#(\1(?:\.[a-z][A-Za-z0-9]{0,63}(?:\[x\])?){1,8})$/; + +/** A question's definition as stored: http://hl7.org/fhir/StructureDefinition/{Type}#{path}. */ +function definitionUri(path) { + const m = DEFINITION_RE.exec(path); + return m ? `http://hl7.org/fhir/StructureDefinition/${m[1]}#${path}` : null; +} + +/** A stored definition as the editor shows it (the path), or null when it isn't one of ours. */ +function definitionPath(uri) { + const m = typeof uri === 'string' ? DEFINITION_URI_RE.exec(uri) : null; + return m ? m[2] : null; +} + +/** A new linkId: random, so one is never used again for another question. */ +function newLinkId(used) { + let id; + do { + id = 'q' + crypto.randomBytes(4).toString('hex'); + } while (used.has(id)); + return id; +} + +/** A Coding as given: {system, code[, display]}, or null when it isn't one. */ +function codingOf(c) { + if (!isObject(c)) { + return null; + } + const system = typeof c.system === 'string' ? c.system.trim() : ''; + const code = typeof c.code === 'string' ? c.code.trim() : ''; + if (!system || !code || system.length > 255 || code.length > 255) { + return null; + } + const display = typeof c.display === 'string' && c.display.trim() ? c.display.trim().substring(0, MAX_TEXT) : null; + return display ? { system, code, display } : { system, code }; +} + +/** The contained Questionnaire, or null. */ +function questionnaireOf(sd) { + return (Array.isArray(sd?.contained) ? sd.contained : []).find(r => isObject(r) && r.resourceType === 'Questionnaire' && r.id === Q_ID) || null; +} + +/** A Questionnaire item as the editor has a question. */ +function questionOf(item) { + const ext = Array.isArray(item.extension) ? item.extension : []; + return { + linkId: item.linkId, + text: typeof item.text === 'string' ? item.text : '', + type: item.type, + definition: item.definition !== undefined ? (definitionPath(item.definition) || item.definition) : '', + answers: (Array.isArray(item.answerOption) ? item.answerOption : []).map(a => a?.valueCoding).filter(isObject), + units: ext.filter(e => isObject(e) && e.url === UNIT_OPTION).map(e => e.valueCoding).filter(isObject) + }; +} + +/** The sub-extensions of an extension with a url. */ +function subs(ext, url) { + return (Array.isArray(ext?.extension) ? ext.extension : []).filter(e => isObject(e) && e.url === url); +} + +/** + * A profile's guided input, as the editor has it, in order. + * @returns {Array<{section: Coding, questions: Array<{linkId, text, type, definition, answers, units}>, resource: string|null, code: Coding|null}>} + */ +function guidesOf(sd) { + const items = new Map(); + for (const item of Array.isArray(questionnaireOf(sd)?.item) ? questionnaireOf(sd).item : []) { + if (isObject(item) && typeof item.linkId === 'string') { + items.set(item.linkId, item); + } + } + return (Array.isArray(sd?.extension) ? sd.extension : []).filter(e => isObject(e) && e.url === INPUT_GUIDE).map(ext => ({ + section: subs(ext, 'section')[0]?.valueCoding || null, + questions: subs(ext, 'question').map(e => items.get(e.valueId)).filter(Boolean).map(questionOf), + resource: subs(ext, 'resource')[0]?.valueCode || null, + code: subs(ext, 'code')[0]?.valueCoding || null + })); +} + +/** + * Check guided input from the editor (or an upload), and give each question its linkId: one it + * already has in the profile it replaces is kept, the others get new ones. + * @param {*} list - the guides + * @param {Object|null} previous - the StructureDefinition being replaced + * @returns {{guides: Array, problems: string[]}} + */ +function checkGuides(list, previous = null) { + const problems = []; + if (list === undefined || list === null) { + return { guides: [], problems }; + } + if (!Array.isArray(list)) { + return { guides: [], problems: ['The guided input must be a list'] }; + } + if (list.length > MAX_GUIDES) { + problems.push(`There can be no more than ${MAX_GUIDES} input guides`); + } + const known = new Set(guidesOf(previous).flatMap(g => g.questions.map(q => q.linkId))); + const used = new Set(); + const guides = []; + list.slice(0, MAX_GUIDES).forEach((g, gi) => { + const at = `Input guide ${gi + 1}`; + if (!isObject(g)) { + problems.push(`${at} is not an object`); + return; + } + const section = codingOf(g.section); + if (!section) { + problems.push(`${at} has no section (a system and code)`); + } + const resource = typeof g.resource === 'string' && g.resource ? g.resource : null; + if (resource && !GUIDE_RESOURCES.some(r => r.code === resource)) { + problems.push(`${at} makes a resource this server doesn't know: '${resource}' (${GUIDE_RESOURCES.map(r => r.code).join(', ')})`); + } + let code = null; + if (g.code !== undefined && g.code !== null && g.code !== '') { + code = codingOf(g.code); + if (!code) { + problems.push(`${at} has a code that isn't a system and code`); + } else if (!resource) { + problems.push(`${at} has a code, but no resource: the code is the resource's`); + } + } + const qs = Array.isArray(g.questions) ? g.questions : []; + if (qs.length === 0) { + problems.push(`${at} has no questions`); + } else if (qs.length > MAX_QUESTIONS) { + problems.push(`${at} has more than ${MAX_QUESTIONS} questions`); + } + const questions = []; + qs.slice(0, MAX_QUESTIONS).forEach((q, qi) => { + const qat = `${at}, question ${qi + 1}`; + if (!isObject(q)) { + problems.push(`${qat} is not an object`); + return; + } + const text = typeof q.text === 'string' ? q.text.trim() : ''; + if (!text) { + problems.push(`${qat} has no text`); + } else if (text.length > MAX_TEXT) { + problems.push(`${qat}'s text is longer than ${MAX_TEXT} characters`); + } + const type = q.type; + if (!QUESTION_TYPES.includes(type)) { + problems.push(`${qat} has no type (${QUESTION_TYPES.join(', ')})`); + } + const definition = typeof q.definition === 'string' ? q.definition.trim() : ''; + if (definition && !DEFINITION_RE.test(definition)) { + problems.push(`${qat}'s definition is not a path in a resource, like Condition.onset[x]`); + } + const answers = []; + for (const a of Array.isArray(q.answers) ? q.answers.slice(0, MAX_ANSWERS) : []) { + const c = codingOf(a); + if (c) { + answers.push(c); + } else { + problems.push(`${qat} has an answer that isn't a system and code`); + } + } + const units = []; + for (const u of Array.isArray(q.units) ? q.units.slice(0, MAX_ANSWERS) : []) { + const c = codingOf(u); + if (c) { + units.push(c); + } else { + problems.push(`${qat} has a unit that isn't a system and code`); + } + } + if (type === 'choice' && answers.length === 0) { + problems.push(`${qat} is a choice, but has no answers to choose from`); + } + if (type !== 'choice' && answers.length) { + problems.push(`${qat} has answers, but only a choice can have them`); + } + if (type !== 'quantity' && units.length) { + problems.push(`${qat} has units, but only a quantity can have them`); + } + let linkId = typeof q.linkId === 'string' && known.has(q.linkId) && !used.has(q.linkId) ? q.linkId : null; + if (!linkId) { + linkId = newLinkId(new Set([...known, ...used])); + } + used.add(linkId); + questions.push({ linkId, text, type, definition, answers, units }); + }); + guides.push({ section, questions, resource, code: resource ? code : null }); + }); + return { guides, problems }; +} + +/** The contained Questionnaire and the input-guide extensions for guided input (none for none). */ +function guideResources(guides) { + if (!Array.isArray(guides) || guides.length === 0) { + return {}; + } + const item = guides.flatMap(g => g.questions.map(q => { + const it = {}; + if (q.units && q.units.length) { + it.extension = q.units.map(u => ({ url: UNIT_OPTION, valueCoding: u })); + } + it.linkId = q.linkId; + if (q.definition) { + it.definition = definitionUri(q.definition); + } + it.text = q.text; + it.type = q.type; + if (q.answers && q.answers.length) { + it.answerOption = q.answers.map(a => ({ valueCoding: a })); + } + return it; + })); + return { + contained: [{ resourceType: 'Questionnaire', id: Q_ID, status: 'active', item }], + extension: guides.map(g => ({ + url: INPUT_GUIDE, + extension: [ + { url: 'questionnaire', valueCanonical: `#${Q_ID}` }, + ...g.questions.map(q => ({ url: 'question', valueId: q.linkId })), + { url: 'section', valueCoding: g.section }, + ...(g.resource ? [{ url: 'resource', valueCode: g.resource }] : []), + ...(g.resource && g.code ? [{ url: 'code', valueCoding: g.code }] : []) + ] + })) + }; +} + +const Q_KEYS = new Set(['resourceType', 'id', 'status', 'item']); +const ITEM_KEYS = new Set(['extension', 'linkId', 'definition', 'text', 'type', 'answerOption']); +const GUIDE_SUBS = new Set(['questionnaire', 'question', 'section', 'resource', 'code']); + +/** + * An uploaded profile's guided input, as the editor's (linkIds dropped, so they are assigned + * afresh), and what is wrong with it: anything more than this server makes is refused, as is a + * guide naming a question the Questionnaire doesn't have. + */ +function guidesFromUpload(sd) { + const problems = []; + const exts = sd.extension === undefined ? [] : sd.extension; + if (!Array.isArray(exts) || exts.some(e => !isObject(e) || e.url !== INPUT_GUIDE)) { + problems.push(`Its only extensions may be input guides (${INPUT_GUIDE})`); + return { guides: [], problems }; + } + const contained = sd.contained === undefined ? [] : sd.contained; + if (!Array.isArray(contained) || contained.length > 1 || (contained.length === 1 && !(isObject(contained[0]) && contained[0].resourceType === 'Questionnaire' && contained[0].id === Q_ID))) { + problems.push(`It may contain only the input guides' Questionnaire (#${Q_ID})`); + return { guides: [], problems }; + } + if (exts.length && !contained.length) { + problems.push(`It has input guides, but no Questionnaire (#${Q_ID})`); + return { guides: [], problems }; + } + const q = contained[0]; + const items = new Map(); + if (q) { + const extraQ = Object.keys(q).filter(k => !Q_KEYS.has(k)); + if (extraQ.length) { + problems.push(`Its Questionnaire has more than input guides use: ${extraQ.join(', ')}`); + } + (Array.isArray(q.item) ? q.item : []).forEach((item, i) => { + if (!isObject(item) || typeof item.linkId !== 'string') { + problems.push(`Its Questionnaire's item ${i + 1} has no linkId`); + return; + } + const extra = Object.keys(item).filter(k => !ITEM_KEYS.has(k)); + if (extra.length) { + problems.push(`Question '${item.linkId}' has more than input guides use: ${extra.join(', ')}`); + } + if ((Array.isArray(item.extension) ? item.extension : []).some(e => !isObject(e) || e.url !== UNIT_OPTION)) { + problems.push(`Question '${item.linkId}' has an extension other than ${UNIT_OPTION}`); + } + if ((Array.isArray(item.answerOption) ? item.answerOption : []).some(a => !isObject(a) || Object.keys(a).some(k => k !== 'valueCoding'))) { + problems.push(`Question '${item.linkId}' has an answer that isn't a Coding`); + } + if (item.definition !== undefined && !definitionPath(item.definition)) { + problems.push(`Question '${item.linkId}' has a definition that isn't http://hl7.org/fhir/StructureDefinition/{type}#{path}`); + } + items.set(item.linkId, item); + }); + } + const guides = exts.map((ext, i) => { + const at = `Input guide ${i + 1}`; + const all = Array.isArray(ext.extension) ? ext.extension : []; + const odd = all.filter(e => !isObject(e) || !GUIDE_SUBS.has(e.url)); + if (odd.length || Object.keys(ext).some(k => k !== 'url' && k !== 'extension')) { + problems.push(`${at} has more than questionnaire, question, section, resource and code`); + } + if (subs(ext, 'questionnaire').length !== 1 || subs(ext, 'questionnaire')[0].valueCanonical !== `#${Q_ID}`) { + problems.push(`${at} must name the Questionnaire #${Q_ID}, once`); + } + for (const u of ['section', 'resource', 'code']) { + if (subs(ext, u).length > 1) { + problems.push(`${at} has more than one ${u}`); + } + } + const questions = []; + for (const e of subs(ext, 'question')) { + const item = items.get(e.valueId); + if (!item) { + problems.push(`${at} names question '${e.valueId}', which the Questionnaire doesn't have`); + } else { + const qn = questionOf(item); + delete qn.linkId; + questions.push(qn); + } + } + return { + section: subs(ext, 'section')[0]?.valueCoding, + questions, + resource: subs(ext, 'resource')[0]?.valueCode || null, + code: subs(ext, 'code')[0]?.valueCoding || null + }; + }); + return { guides, problems }; +} + +/** + * The order the guided input is shown in: grouped by section - the IPS sections in their + * order first, then the others as they first appear - and in a section, the guides' own order. + * @returns {Array<{section: Coding, guides: Array<{guide, index}>}>} index: the guide's place in the profile + */ +function guideGroups(guides, ipsOrder) { + const groups = new Map(); + guides.forEach((guide, index) => { + const key = `${guide.section?.system}|${guide.section?.code}`; + if (!groups.has(key)) { + groups.set(key, { section: guide.section, guides: [], first: index }); + } + groups.get(key).guides.push({ guide, index }); + }); + const rank = (g) => { + const i = g.section?.system === LOINC ? ipsOrder.indexOf(g.section.code) : -1; + return i >= 0 ? i : ipsOrder.length + g.first; + }; + return [...groups.values()].sort((a, b) => rank(a) - rank(b)); } /** @@ -499,7 +915,8 @@ function describeResource(r, titleOf) { } module.exports = { - SYSTEMS, IPS_SECTIONS, RESOURCE_TYPES, BUNDLE, MAX_CONSTRAINTS, ID_RE, migrate, + SYSTEMS, IPS_SECTIONS, SECTION_CHECKS, RESOURCE_TYPES, + INPUT_GUIDE, UNIT_OPTION, QUESTION_TYPES, GUIDE_RESOURCES, guidesOf, checkGuides, guideGroups, definitionUri, definitionPath, BUNDLE, MAX_CONSTRAINTS, ID_RE, migrate, parseResourceShape, resourceShapeExpression, kindOf, describeResource, parseShape, shapeExpression, parseCard, cardText, expressionProblem, nameFromTitle, newId, checkInput, build, constraintsOf, fromUpload, describePart diff --git a/ips/readme.md b/ips/readme.md index f5fcfe32..dfb50b59 100644 --- a/ips/readme.md +++ b/ips/readme.md @@ -101,20 +101,21 @@ CapabilityStatement): GET /ips/{code}/Bundle/{id}/$document?source=modified&system-sign=true&patient-notes=true POST /ips/{code}/Bundle/{id}/$document (a Parameters resource) -Parameters: `source` (`original`, the default, or `modified`), and the booleans `user-sign` -(as the owner of the API token in `Authorization: Bearer` - 401 without one, 409 if they have -no key pair to sign with), `system-sign`, `patient-notes` (the patient's comments; nothing -added, and no error, when there are none) and `regenerate-narrative`. The copy is made as the -web page makes it: any patient notes section (LOINC 51855-5) removed, the narrative regenerated, -signed, then the patient's comments added as the first section (not signed). What comes back is -chosen by `Accept`, or `_format` (a short name or the mime type): `application/fhir+json` or -`application/json` (`json`, the default), `application/zip` (`zip`), `application/pdf` -(`pdf`), `application/smart-health-link` (`shl`) or `application/verified-health-link` -(`vhl`); anything else is 406. The ZIP and the PDF are made on the server (`ips/export.js`): -the PDF is the same content as the browser's - the title, the patient, the date and each -section's narrative, with the document attached - laid out as text in the standard PDF fonts -(tables as rows of cells, no images; characters outside Windows-1252 show as `?`). An SHL or -VHL answer is the QR code as a PNG, with the link it carries in `X-Health-Link`, the manifest in +Parameters: `source` (`original`, the default, or `modified`), `format-type` (below), and the +booleans `user-sign` (as the owner of the API token in `Authorization: Bearer` - 401 without one, +409 if they have no key pair to sign with), `system-sign`, `patient-notes` (the patient's +comments; nothing added, and no error, when there are none) and `regenerate-narrative`. The copy +is made as the web page makes it: any patient notes section (LOINC 51855-5) removed, the +narrative regenerated, signed, then the patient's comments added as the first section (not +signed). What comes back is chosen by `format-type` when it is given - `json`, `pdf`, `zip`, +`shl` or `vhl` - whatever `Accept` says; otherwise by `Accept` (or `_format`, which takes the same +mime types): `application/fhir+json` or `application/json` (the default), `application/zip`, +`application/pdf`, or `image/png` (a VHL's QR code; `format-type=shl` for an SHL's); anything +else is 406. The ZIP and the PDF are made on the server (`ips/export.js`): the PDF is the same +content as the browser's - the title, the patient, the date and each section's narrative, with +the document attached - laid out as text in the standard PDF fonts (tables as rows of cells, no +images; characters outside Windows-1252 show as `?`). An SHL or VHL answer is the QR code as a +PNG (`image/png`), with the link it carries in `X-Health-Link`, the manifest in `X-Health-Link-Manifest` and the expiry in `X-Health-Link-Expires`. `$document` shares the rate limit of sharing and of the web page's signed downloads. @@ -779,7 +780,7 @@ come back as a list for the page to show. A clinical profile says what a kind of clinical document is expected to contain. It is a StructureDefinition: a profile on Bundle (the document) with one element, the root, whose constraints are the expectations. Each constraint has a description and a FHIRPath expression on the document. Profiles are shared across all projects (`/ips/StructureDefinition`). Everyone can see them; only the administrator creates, edits, uploads and deletes them. -The administrator edits only the title and the constraints. The server sets everything else: +The administrator edits only the title, the constraints and the guided input (below). The server sets everything else: - the id: `profile-` plus a random private id; - the url: `[base]/ips/StructureDefinition/profile-{id}`, fixed when the profile is made; @@ -790,10 +791,23 @@ The administrator edits only the title and the constraints. The server sets ever Most expectations take one of two shapes, using the module's own [FHIRPath functions](#fhirpath-functions): ``` -Bundle.section(system, code [, min, max]).exists() -Bundle.section(system, code [, min, max]).entry(system, code [, min, max]).exists() +Bundle.section(system, code).exists() +Bundle.section(system, code).isKnown() +Bundle.section(system, code).where(isKnown() and sameSubject()).exists() +Bundle.section(system, code)[.where(checks)].entry(system, code [, min, max]).exists() ``` +The section has no bounds (more than one of the same section is a corner case IPS documents +don't have: a `section()` with bounds is an other rule). What it must be is up to three checks, +in this order: `isKnown()` (must be asked/known), `hasData()` (must have supporting entries) +and `sameSubject()` (about the same Patient). One check on its own is the rule; more than one, +or any with an entry part, go in a `where()`. `isKnown()`: the section has no emptyReason, or a +nil known one (`list-empty-reason#nilknown`) - any other emptyReason is not known. `hasData()`: +the section has an emptyReason, or else entries. `sameSubject()` on a section: it has no focus, +or its focus is the Composition's subject. On no section they give nothing (so the rule fails), +and on anything that isn't a section, false. They are the Java `DocumentFunctions`' (the +validator's) as well as `ips/fhirpath-ips.js`'s. + Rules about the resources in the document, whatever section they are in, take a third shape: ``` @@ -802,20 +816,59 @@ Bundle.resources(system, code [, type]).{the rest of the rule} Entries and resources can be matched by value set instead of by one code: `Bundle.section(...).entryIn(valueSet [, min, max]).exists()`, and `Bundle.resourcesIn(valueSet [, type])...`. Sections are always matched by code. An example rule: `Bundle.resources('http://snomed.info/sct', '38341003', 'Condition').all(clinicalStatus.coding.code = 'active')`. -The editor (`/ips/StructureDefinition/new`, or Edit on a profile) is in three parts, and so is the page that shows a profile: +A new profile is made on the list page (`/ips/StructureDefinition`) from just a title (`POST /ips/StructureDefinition` with `{title}`), and its rules and guided input are added on its own page, which is in four parts: -- **Required sections and entries:** the first two shapes, each a row of a table with four columns (the section, its cardinality, the entry code and its cardinality). +- **Required sections and entries:** the first shape, each a row of a table: the section, with its checks as three checkboxes in a row (must be asked/known, must have supporting entries, about the same Patient), the entry code and its cardinality. - **Rules about resources:** the third shape, each a row of a table with four columns (the type, which is optional, the system, the code, and the rest of the rule as FHIRPath starting with a dot). - **Other rules:** any other FHIRPath. +- **Guided input:** below. -The page that shows a profile is the same for everyone. Its first part is a table of three columns: the **Expectation** (the description), the **Section** (an IPS section by its title, or `system|code`) and the **Entry** (`Code is system|code`, or `Code is in` a value set, by its title, or its URL when the title isn't known). A code system is shown by name when it is a known one. A cardinality, `[m..n]`, follows a section or an entry unless it is `1..1` or not given (none means at least one). The second part is also a table of three columns: the **Expectation**, the **Resource Set** (the type, as `MedicationAdministrations where` or `Any resource where`, then the code as in the Entry column) and the **Rule**, which is the rest of the expression in words where it is one of these: `.exists()` is "Must be present somewhere"; `.all(sameSubject())` is "Patient must match the Document"; `.x.exists()` and `.x.y.exists()` are "Must have an x" and "Must have an x.y" (no deeper); `.conformsTo(url)` (or `.all(conformsTo(url))`) is "Conform to" the profile, named by its title when it is one of the clinical profiles or by its jurisdiction and package when it is a national profile; and `.category.hasCoding(system, code [, version])` (or inside `.all()`) is "Has category system|code". Any other rest is shown as FHIRPath, and so are the other rules. On the same page the administrator edits the rules one at a time: each row has Edit and Delete, and each part has an Add button. Add and Edit open a dialog for the one rule - the expectation, then the parts of the rule, each with what it means (for a rule about resources, what must be true of them is a choice: present somewhere, the patient matches the document's, an element, conformance to a profile, a category, or other FHIRPath), and the FHIRPath it makes - and Save stores that one rule by itself (`POST /ips/StructureDefinition/{id}/constraint` to add, `.../constraint/{key}` to change, `.../constraint/{key}/delete` to delete). An edited rule keeps its key. The full editor is still there (Edit all), for the title, or for many changes at once. +The page that shows a profile is the same for everyone. Its first part is a table of three columns: the **Expectation** (the description), the **Section** (an IPS section by its title, or `system|code`) and the **Entry** (`Code is system|code`, or `Code is in` a value set, by its title, or its URL when the title isn't known). A code system is shown by name when it is a known one. A section's checks follow it, in words (must be asked/known, must have supporting entries, about the same Patient). A cardinality, `[m..n]`, follows an entry unless it is `1..1` or not given (none means at least one). The second part is also a table of three columns: the **Expectation**, the **Resource Set** (the type, as `MedicationAdministrations where` or `Any resource where`, then the code as in the Entry column) and the **Rule**, which is the rest of the expression in words where it is one of these: `.exists()` is "Must be present somewhere"; `.all(sameSubject())` is "Patient must match the Document"; `.x.exists()` and `.x.y.exists()` are "Must have an x" and "Must have an x.y" (no deeper); `.conformsTo(url)` (or `.all(conformsTo(url))`) is "Conform to" the profile, named by its title when it is one of the clinical profiles or by its jurisdiction and package when it is a national profile; and `.category.hasCoding(system, code [, version])` (or inside `.all()`) is "Has category system|code". Any other rest is shown as FHIRPath, and so are the other rules. On the same page the administrator edits the rules one at a time: each row has Edit and Delete, and each part has an Add button. Add and Edit open a dialog for the one rule - the expectation, then the parts of the rule, each with what it means (for a rule about resources, what must be true of them is a choice: present somewhere, the patient matches the document's, an element, conformance to a profile, a category, or other FHIRPath), and the FHIRPath it makes - and Save stores that one rule by itself (`POST /ips/StructureDefinition/{id}/constraint` to add, `.../constraint/{key}` to change, `.../constraint/{key}/delete` to delete). An edited rule keeps its key. Rename changes the title (`POST .../title`; the name follows it). There is no full editor any more: an old link to one (`.../edit`) lands on the profile's page. A rule moves between the parts when it is switched between table and FHIRPath, and it lands in the part whose shape it fits. A section is one of the IPS sections, or any code in any system. An entry or resource code is a code in a named code system (SNOMED CT, LOINC, ICD-10...) or in any other given by URL, and it is looked up on the terminology server (`GET /ips/lookup?system=&q=`, for the administrator only). Choosing "In a value set..." as the system matches entries or resources by value set instead. The code box becomes a value set search (`GET /ips/lookup-vs?q=`, for the administrator only): this module's own value sets that match the title come first, then the terminology server's (a `ValueSet?title=` search). A suggestion shows its title, with its URL underneath. A canonical can also be typed or pasted in, with `|version` to pin a version. When the editor opens, it looks up the title of each value set by URL (`?url=`). If the terminology server doesn't know a value set, it says so as a warning, not an error: the value set has to be known when documents are checked, not when the profile is saved. A cardinality is blank (no bounds) or `min..max`, where max may be `*`. Before a profile is saved, every expression is parsed and run once against an empty document. That catches unknown functions and wrong numbers of arguments as well as syntax errors. -A profile can be downloaded as JSON (`?download=1`), and a downloaded profile can be uploaded again as a new profile, with a new id, url and keys. An upload must be no more than a profile like this: a profile on Bundle with no snapshot, and one differential element (the root) carrying constraints that have only a key, an `error` severity, a description, an expression and a source. Anything more is rejected, with the reasons. A profile downloaded when clinical profiles were on Composition is accepted and moved onto Bundle, as profiles already stored are when the server starts: `Composition.section(...)` becomes `Bundle.section(...)`, and any other `Composition.x` becomes `Bundle.entry.resource.ofType(Composition).x`. +A profile can be downloaded as JSON (`?download=1`), and a downloaded profile can be uploaded again as a new profile, with a new id, url and keys. An upload must be no more than a profile like this: a profile on Bundle with no snapshot, and one differential element (the root) carrying constraints that have only a key, an `error` severity, a description, an expression and a source - and guided input, as below. Anything more is rejected, with the reasons. A profile downloaded when clinical profiles were on Composition is accepted and moved onto Bundle, as profiles already stored are when the server starts: `Composition.section(...)` becomes `Bundle.section(...)`, and any other `Composition.x` becomes `Bundle.entry.resource.ofType(Composition).x`. As FHIR: `GET /ips/StructureDefinition` is a searchset of them all, and `GET /ips/StructureDefinition/{id}` is one of them. +### Guided input + +Guided input is questions for the people filling a document in, about a section. When a profile +has any, it contains a Questionnaire (`#Q`), and has an extension +`http://www.healthintersections.com.au/fhir/StructureDefinition/input-guide` for each guide, in +order, with these sub-extensions: + +- `questionnaire` (canonical, 1..1): `#Q`; +- `question` (id, 1..*): the linkIds of its questions in the Questionnaire, in order. The server + makes them (`q` and 8 random hex digits, so one is never used again), keeps a question's linkId + for as long as the question is kept, and takes a question's item out of the Questionnaire when + the question goes (and the Questionnaire, when the last guide goes). People never see them; +- `section` (Coding, 1..1): the section the questions are about - one of the IPS sections, or any + code, as `system|code`, so sections other than the IPS ones can be guided too; +- `resource` (code, 0..1): what the answers make - `Condition:problem`, `Condition:diagnosis`, + `Observation:vitals`, `MedicationStatement` or `AllergyIntolerance` (the class after the colon + changes how it is used); +- `code` (Coding, 0..1): the resource's code - only with a resource. + +A question has text, a type - `display`, `boolean`, `quantity`, `date` or `choice` - and +optionally a definition: a path in a resource (`Condition.onset[x]`), kept in the +Questionnaire as `http://hl7.org/fhir/StructureDefinition/Condition#Condition.onset[x]`. A +choice has its answers (Codings, as `answerOption`); a quantity may name its units (Codings, +UCUM by default, as `questionnaire-unitOption` extensions). + +The page shows the guided input as a table - Section, Questions (each with its type), Resource, +Code - grouped by section: the IPS sections in the IPS order, then other sections as they first +appear; in a section, the guides' own order. The administrator adds, edits and deletes a guide at +a time, and moves it up or down within its section (`POST .../guide` to add, `.../guide/{n}` to +change, `.../guide/{n}/delete`, `.../guide/{n}/move` with `direction` up or down - n is the +guide's place among the extensions). The dialog has the section (the same chooser as the rules), +the questions (added, deleted and moved up and down; answers and units with the code system and +code lookup), the resource, and its code. Saving a profile's rules or title leaves its guided +input as it is. An upload keeps its guided input, with new linkIds; anything more than this - an +extension other than input-guide, a contained resource other than `#Q`, more in the +Questionnaire or its items than the above, or a guide naming a question the Questionnaire +doesn't have - is refused. + ## National profiles A national profile is the profile a national implementation guide defines for an IPS document. Each has five parts: @@ -901,14 +954,16 @@ runaway statement would otherwise hold the server. ## FHIRPath functions -`ips/fhirpath-ips.js` adds two functions to fhirpath.js, for expressions on IPS documents: +`ips/fhirpath-ips.js` adds these functions to fhirpath.js, for expressions on IPS documents (the Java `DocumentFunctions` in org.hl7.fhir.core, which the validator runs, has the same): - `section(system, code [, min, max])`: the input is documents (Bundles) or Compositions. On a document it moves into the document's Composition by itself, which is why a clinical profile's rules, evaluated on the document, can say `Bundle.section(...)`. For each input, it returns the Composition's sections, nested ones included, whose `code` has a coding with that system and code. - `resources(system, code [, type])`: the input is documents, or anything in one (a Composition, say). It returns every resource in the document whose `code`, `medicationCodeableConcept` or `vaccineCode` has a coding with that system and code, and that is of the given type when a type is given. - `entryIn(valueSet [, min, max])` and `resourcesIn(valueSet [, type])`: as `entry()` and `resources()`, but they match a code in a value set (a canonical, with or without `|version`) rather than one given code. A resource is in when any coding of its code is. These two ask a terminology server, so the evaluation must be asynchronous (`evaluateAsync`), with a `membership` function in the options. A `MembershipSession` (`ips/membership.js`, made by the module's `membershipSession()`) provides one: it asks `ValueSet/$validate-code` with the CodeableConcept, only for what a rule actually reaches. Within a session, each question is asked once, and there's a budget of 500 per document. Definite answers are also kept in the module's cache, so the next document doesn't ask again. When the server can't answer (it doesn't know the value set, say), the answer is "not a member" for that run, and the session's `unresolved()` lists the value set and the server's message, so a rule that failed for that reason can be told apart from one that plainly failed. The module's own value sets (`ips/valuesets/`) are sent with the question, so any server can answer for them; any other value set must be one the server knows. - `entry(system, code [, min, max])`: the input is sections, usually from `section()`. For each one, it returns its resolved entries whose `code`, `medicationCodeableConcept` or `vaccineCode` has a coding with that system and code. `medicationReference` is not followed. +- `isKnown()` and `hasData()`: the input is sections. `isKnown()` is true when each has no `emptyReason`, or a nil known one (`list-empty-reason#nilknown`); `hasData()` when each has an `emptyReason`, or else entries. Empty on no input; false for anything that isn't a section of a Composition. +- `sameSubject([other])`: on a section, true when it has no `focus`, else whether the focus is the subject of `other` (or, without it, of the section's Composition); on a resource, whether its `subject` (or `patient`) is `other`'s (or, without it, the document's Composition's). References are the same when their reference strings are, else when their identifiers' system and value are. Empty when the input or `other` isn't one item, or a subject is missing. -`min` and `max` are optional (both or neither), and `max` may be `'*'`. The bounds apply to each input item: when the number found is outside them, that item adds nothing. That isn't an error. References are resolved in the Bundle the section is in, or failing that the Bundle the expression was evaluated on: +`min` and `max` are optional (both or neither), and `max` may be `'*'`. Without them, `section()` is `1..1` - a document with two of the same section has none, for a rule - and `entry()` and `entryIn()` are `0..*` (no bounds), as in the Java `DocumentFunctions`. The bounds apply to each input item: when the number found is outside them, that item adds nothing. That isn't an error. References are resolved in the Bundle the section is in, or failing that the Bundle the expression was evaluated on: - absolute `fullUrl`s (`urn:uuid:`, `http…`) match as they are; - a relative `Type/id` is resolved against the base of the Composition's `fullUrl`, or matched by type and id when there's no usable base; diff --git a/ips/render.js b/ips/render.js index d5b12d9d..30ee2e15 100644 --- a/ips/render.js +++ b/ips/render.js @@ -24,7 +24,7 @@ const { checkNarrative } = require('../library/narrative-check'); const { tokenConfigured } = require('../library/request-token'); const { STATUSES } = require('./search'); const profiles = require('./profiles'); -const { terminologyOf, systemName, describeVersion, linkForSystem, linkForCode, isExternalSystem } = require('./terminology'); +const { terminologyOf, systemName, describeVersion, linkForSystem, linkForCode, isExternalSystem, SECTION_ORDER } = require('./terminology'); const { issueSummary, checkOf, translationOf } = require('./pipeline'); const { jurisdiction } = require('./jurisdictions'); const { summaryOf, STEP_TIMINGS_SAMPLE } = require('./store'); @@ -161,6 +161,7 @@ const STYLE = ` .ips-pf-grid td.ips-pf-card { width: 7em; } .ips-pf-grid .ips-ed-input { width: 100%; box-sizing: border-box; } .ips-pf-pair { display: flex; gap: 4px; } + .ips-pf-checks { display: flex; flex-wrap: wrap; gap: 6px 20px; margin-top: 6px; } .ips-pf-check { font-weight: normal; margin: 0; white-space: nowrap; } .ips-pf-pair select { max-width: 13em; } .ips-pf-display { font-size: 85%; color: #555; margin-top: 2px; min-height: 1em; } .ips-pf-expr { font-family: monospace; font-size: 85%; color: #666; margin-top: 4px; word-break: break-all; } @@ -171,7 +172,11 @@ const STYLE = ` .ips-pf-rule td.ips-pf-actions { padding-top: 1px; padding-bottom: 1px; } .ips-pf-part-head { display: flex; align-items: baseline; gap: 12px; margin-top: 18px; } .ips-pf-part-head h4 { margin: 0 0 6px; } - .ips-pf-part-head .ips-pf-add { font-size: 80%; padding: 0 8px; line-height: 1.6; } + .ips-pf-part-head .ips-pf-add, .ips-pf-part-head .ips-pf-add-guide { font-size: 80%; padding: 0 8px; line-height: 1.6; } + .ips-pf-questions { margin: 0; padding-left: 18px; } .ips-pf-guides td { vertical-align: top; } + .ips-pf-rename { display: inline-block; } .ips-pf-rename summary { list-style: none; display: inline-block; } .ips-pf-rename summary::-webkit-details-marker { display: none; } + .ips-pf-question { border: 1px solid #dee2e6; border-radius: 4px; padding: 6px 8px; margin-bottom: 6px; } .ips-pf-qhead { display: flex; gap: 4px; align-items: center; } + .ips-pf-list-row { display: flex; gap: 4px; align-items: flex-start; margin-bottom: 4px; } .ips-pf-rule .ips-pf-actions .btn { font-size: 75%; padding: 0 5px; line-height: 1.5; border-radius: 3px; vertical-align: baseline; } .ips-pf-how { align-items: center; gap: 8px; margin-top: 6px; } .ips-pf-how input { width: 7em; flex: none; } .ips-pf-how .ips-pf-hint { margin: 0; } .ips-pf-dialog { width: min(760px, 95vw); max-height: 90vh; padding: 0; border: 1px solid #bbb; border-radius: 6px; box-shadow: 0 8px 30px rgba(0,0,0,0.3); } @@ -528,9 +533,9 @@ function projectDocs(project, ctx) { '
| Request | |
|---|---|
POST ${purl}/Bundle | submit a document${submitNote(project)}; the response is the stored document, with its id |
GET ${purl}/Bundle/{id} | read a document - JSON for a FHIR client, this web page for a browser (?_format=json forces JSON, ?download=1 downloads it) |
GET ${purl}/Bundle/{id}/$document?... | the document as the source view gives it for download or sharing: parameters source (original | modified), ` +
+ ` |
GET ${purl}/Bundle/{id}/$document?... | the document as the source view gives it for download or sharing: parameters source (original | modified), format-type (json | pdf | zip | shl | vhl), ` +
'user-sign (as the owner of the API token in Authorization: Bearer), system-sign, patient-notes, regenerate-narrative (true | false); ' +
- 'by Accept (or _format) the JSON, application/zip, application/pdf, or the QR code (a PNG) of an SHL (application/smart-health-link) or VHL (application/verified-health-link) - ' +
+ 'the JSON, a ZIP, a PDF, or the QR code (image/png) of an SHL or VHL: by format-type, else Accept (or _format) - image/png is a VHL\'s - ' +
'OperationDefinition |
GET ${purl}/Bundle?... | search: Bundle's search parameters (_id, identifier, _lastUpdated, composition), chained to the Composition and Patient as ` +
'composition.date, composition.title, composition.patient.name, composition.patient.gender, composition.patient.birthdate, composition.patient.identifier, ...; ' +
@@ -1998,7 +2003,8 @@ function renderProfiles(list, ctx) {
h += '';
if (ctx.user?.isAdmin) {
h += '' +
- `New profile ` +
+ ' ' +
+ ' ' +
'' +
' ';
}
@@ -2021,6 +2027,17 @@ function renderProfiles(list, ctx) {
h += ``;
- h += ``;
- return h;
-}
-
// ---- the SHL viewer --------------------------------------------------------------------------
const TRACE_LEVELS = {
@@ -3267,5 +3315,5 @@ module.exports = {
analysisOk,
renderHome, renderProjects, renderProject, renderSubmit, renderSettings, renderDocument,
assembledNarrative, renderStructure, renderAnalysis, renderTerminology, renderTranslation, renderGenerated, renderAi, renderPatientComments, PATIENT_COMMENT_MAX, renderValidation, renderNational, renderShare, renderCompose, renderComposeChoice, renderPatientEditor, renderPatients, renderPatient, renderProfileChecks,
- renderProfiles, renderProfile, renderProfileEditor, renderNationalProfiles, renderReports, renderReportDefinition, renderReportEditor, renderProjectReports, renderProjectReport, renderQueue, renderViewerStart, renderView, VIEWS, viewOf
+ renderProfiles, renderProfile, renderNationalProfiles, renderReports, renderReportDefinition, renderReportEditor, renderProjectReports, renderProjectReport, renderQueue, renderViewerStart, renderView, VIEWS, viewOf
};
diff --git a/library/config-check.js b/library/config-check.js
index b5ec1cec..1fbb3650 100644
--- a/library/config-check.js
+++ b/library/config-check.js
@@ -153,7 +153,9 @@ const SERVER = obj({
sharedCache: bool(),
sharedCacheMaxMB: num({ min: 0 }),
cacheAffinity: bool(),
- sharedClosure: bool()
+ sharedClosure: bool(),
+ // the modules the workers run besides tx (library/role.js)
+ workerModules: arr(str({ values: ['tx', 'rest'] }))
})
});
@@ -465,6 +467,31 @@ const MODULES = {
trust: arr(obj({ kid: str({ nonEmpty: true }), name: str(), certFile: str({ nonEmpty: true }), certificate: str({ nonEmpty: true }) }))
}),
validator: validatorSpec
+ }),
+ // rest/README.md: where each endpoint is and which database it uses; the rest of an
+ // endpoint's settings are in its database
+ rest: obj({
+ enabled: bool(),
+ packageServers: arr(url()),
+ endpoints: arr(obj({
+ path: str({ required: true, pattern: /^\/[A-Za-z0-9/_-]*$/, patternText: 'a path like /fhir/r4' }),
+ fhirVersion: str({ pattern: /^\d+\.\d+(\.\d+)?(-[A-Za-z0-9.]+)?$/, patternText: 'a FHIR version like 4.0.1' }),
+ baseUrl: url(),
+ database: obj({
+ type: str({ values: ['sqlite', 'mysql'], required: true }),
+ file: str({ nonEmpty: true }),
+ host: str({ nonEmpty: true }),
+ port: port(),
+ database: str({ nonEmpty: true }),
+ user: str({ nonEmpty: true }),
+ password: retired('MySQL passwords don\'t go in config.json: use passwordEnv (an environment variable) or passwordFile'),
+ passwordEnv: str({ nonEmpty: true }),
+ passwordFile: str({ nonEmpty: true }),
+ connections: int({ min: 1 })
+ }, { required: true }),
+ initialSettings: any(),
+ types: any()
+ }))
})
};
diff --git a/library/fhir-search-values.js b/library/fhir-search-values.js
index 3f64416f..efaa60ef 100644
--- a/library/fhir-search-values.js
+++ b/library/fhir-search-values.js
@@ -8,25 +8,102 @@
* The value-level parts of FHIR search that every module with a search implements the
* same way: date ranges, the comparison prefixes, comma-separated values, and LIKE
* escaping. The SQL that uses them is each module's own (testing/search.js,
- * ips/search.js).
+ * ips/search.js, rest/search/sql.js).
+ *
+ * Every date value is a half-open range of instants [lo, hi) in epoch milliseconds, and
+ * every prefix is one comparison between two ranges (see dateClause, and the rest
+ * module's design: "Date and time search").
*
* @module library/fhir-search-values
*/
const PREFIXES = ['eq', 'ne', 'gt', 'lt', 'ge', 'le', 'sa', 'eb', 'ap'];
+// seconds may be 60: a leap second, which FHIR allows
const DATE_RE = /^(\d{4})(?:-(\d{2})(?:-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(Z|[+-]\d{2}:\d{2})?)?)?)?$/;
+// the smallest and largest instants a JavaScript date can hold: the ends of an open
+// Period. Stored as numbers, never as NULL, so an open-ended Period still compares
+const MIN_INSTANT = -8.64e15;
+const MAX_INSTANT = 8.64e15;
+
+const DAY_MS = 86400000;
+
+/**
+ * UTC milliseconds for a date and time in UTC. Unlike Date.UTC, a year from 0 to 99 is that
+ * year, not 1900 to 1999.
+ */
+function utc(year, month, day, h = 0, mi = 0, s = 0, ms = 0) {
+ const d = new Date(0);
+ d.setUTCFullYear(year, month, day);
+ d.setUTCHours(h, mi, s, ms);
+ return d.getTime();
+}
+
+const offsetFormats = new Map();
+
+/**
+ * The offset of a time zone from UTC at an instant, in milliseconds (local - UTC).
+ * @param {number} instant - epoch ms
+ * @param {string} timeZone - an IANA zone name
+ */
+function zoneOffset(instant, timeZone) {
+ if (!timeZone || timeZone === 'UTC' || timeZone === 'Etc/UTC') {
+ return 0;
+ }
+ let fmt = offsetFormats.get(timeZone);
+ if (!fmt) {
+ fmt = new Intl.DateTimeFormat('en-US', {
+ timeZone, hourCycle: 'h23', year: 'numeric', month: 'numeric', day: 'numeric',
+ hour: 'numeric', minute: 'numeric', second: 'numeric', era: 'short'
+ });
+ offsetFormats.set(timeZone, fmt);
+ }
+ const p = {};
+ for (const part of fmt.formatToParts(new Date(instant))) {
+ p[part.type] = part.value;
+ }
+ let year = parseInt(p.year, 10);
+ if (p.era === 'BC' || p.era === 'B') {
+ year = 1 - year;
+ }
+ const local = utc(year, parseInt(p.month, 10) - 1, parseInt(p.day, 10),
+ parseInt(p.hour, 10), parseInt(p.minute, 10), parseInt(p.second, 10));
+ return local - (instant - (((instant % 1000) + 1000) % 1000));
+}
+
+/**
+ * The UTC instant of a wall-clock time in a time zone. Daylight saving changes are taken
+ * from the time zone database, so local midnight on the day a change happens is right.
+ * @param {number} wall - the wall-clock time as if it were UTC (from utc())
+ * @param {string} timeZone
+ */
+function wallToInstant(wall, timeZone) {
+ if (!timeZone || timeZone === 'UTC' || timeZone === 'Etc/UTC') {
+ return wall;
+ }
+ // two rounds: the offset at the first guess, then at the answer it gives
+ let t = wall - zoneOffset(wall, timeZone);
+ t = wall - zoneOffset(t, timeZone);
+ return t;
+}
+
/**
* The range of instants a FHIR date, dateTime or instant covers, as [lo, hi) in epoch
- * milliseconds. "2026" covers the whole year; "2026-09-24T10:00:00.5Z" covers 100ms.
- * A time with no zone is taken as UTC (FHIR requires a zone, but search values often
- * leave it off).
+ * milliseconds. "2026" covers the whole year; "2026-09-24T10:00:00.5Z" covers 100ms;
+ * milliseconds are the finest grain.
+ *
+ * A value with no zone - a date, a partial date, or a time without one - is taken in the
+ * given time zone (UTC by default): "2026-09-24" runs from local midnight to local
+ * midnight, which is 23 or 25 hours on a day with a daylight saving change.
+ *
+ * A leap second (23:59:60) is the last second of that minute.
*
* @param {string} value
+ * @param {string} [timeZone] - an IANA time zone name; UTC if absent
* @returns {{lo: number, hi: number}|null} null if the value isn't a date
*/
-function dateRange(value) {
+function dateRange(value, timeZone) {
if (typeof value !== 'string') {
return null;
}
@@ -37,28 +114,57 @@ function dateRange(value) {
const [, y, mo, d, h, mi, s, frac, tz] = m;
const year = parseInt(y, 10);
if (!mo) {
- return { lo: Date.UTC(year, 0, 1), hi: Date.UTC(year + 1, 0, 1) };
+ return {
+ lo: wallToInstant(utc(year, 0, 1), timeZone),
+ hi: wallToInstant(utc(year + 1, 0, 1), timeZone)
+ };
}
const month = parseInt(mo, 10) - 1;
if (month < 0 || month > 11) {
return null;
}
if (!d) {
- return { lo: Date.UTC(year, month, 1), hi: Date.UTC(year, month + 1, 1) };
+ return {
+ lo: wallToInstant(utc(year, month, 1), timeZone),
+ hi: wallToInstant(utc(year, month + 1, 1), timeZone)
+ };
}
const day = parseInt(d, 10);
- if (day < 1 || day > new Date(Date.UTC(year, month + 1, 0)).getUTCDate()) {
+ if (day < 1 || day > new Date(utc(year, month + 1, 0)).getUTCDate()) {
return null;
}
if (!h) {
- return { lo: Date.UTC(year, month, day), hi: Date.UTC(year, month, day + 1) };
+ return {
+ lo: wallToInstant(utc(year, month, day), timeZone),
+ hi: wallToInstant(utc(year, month, day + 1), timeZone)
+ };
}
- const zone = tz || 'Z';
- const text = `${y}-${mo}-${d}T${h}:${mi}:${s || '00'}${frac || ''}${zone}`;
- const lo = Date.parse(text);
- if (Number.isNaN(lo) || parseInt(h, 10) > 23 || parseInt(mi, 10) > 59 || (s && parseInt(s, 10) > 59)) {
+ const hour = parseInt(h, 10);
+ const minute = parseInt(mi, 10);
+ let second = s ? parseInt(s, 10) : 0;
+ if (hour > 23 || minute > 59 || second > 60 || (second === 60 && !(hour === 23 && minute === 59))) {
return null;
}
+ if (second === 60) {
+ // a leap second: the last second of the minute
+ second = 59;
+ }
+ const millis = frac ? Math.floor(parseFloat('0' + frac) * 1000) : 0;
+ const wall = utc(year, month, day, hour, minute, second, millis);
+ let lo;
+ if (tz && tz !== 'Z') {
+ const sign = tz[0] === '-' ? -1 : 1;
+ const oh = parseInt(tz.substring(1, 3), 10);
+ const om = parseInt(tz.substring(4, 6), 10);
+ if (oh > 14 || om > 59) {
+ return null;
+ }
+ lo = wall - sign * (oh * 3600000 + om * 60000);
+ } else if (tz === 'Z') {
+ lo = wall;
+ } else {
+ lo = wallToInstant(wall, timeZone);
+ }
let width;
if (!s) {
width = 60000;
@@ -71,6 +177,59 @@ function dateRange(value) {
return { lo, hi: lo + width };
}
+/**
+ * The range a Period covers: from the start's lo to the end's hi, open where either is
+ * missing. A Period ending "2013-01-21" runs to the end of that day.
+ * @param {{start?: string, end?: string}} period
+ * @param {string} [timeZone]
+ * @returns {{lo: number, hi: number}|null}
+ */
+function periodRange(period, timeZone) {
+ if (!period || (!period.start && !period.end)) {
+ return null;
+ }
+ const start = period.start ? dateRange(period.start, timeZone) : null;
+ const end = period.end ? dateRange(period.end, timeZone) : null;
+ if ((period.start && !start) || (period.end && !end)) {
+ return null;
+ }
+ return { lo: start ? start.lo : MIN_INSTANT, hi: end ? end.hi : MAX_INSTANT };
+}
+
+/**
+ * The range for `ap`: the value's range widened on each side by 10% of the distance
+ * between it and now, and never by less than a day.
+ * @param {{lo: number, hi: number}} range
+ * @param {number} [now] - epoch ms
+ */
+function approxDateRange(range, now = Date.now()) {
+ const mid = (range.lo + range.hi) / 2;
+ const widen = Math.max(DAY_MS, Math.abs(now - mid) * 0.1);
+ return { lo: range.lo - widen, hi: range.hi + widen };
+}
+
+/**
+ * The range a decimal number covers by its precision: "1.5" is [1.45, 1.55), "100" is
+ * [99.5, 100.5). An exponent counts too: "1e2" is [50, 150).
+ * @param {string|number} text
+ * @returns {{lo: number, hi: number, value: number}|null}
+ */
+function numberRange(text) {
+ const s = String(text).trim();
+ const m = /^([+-]?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/.exec(s);
+ if (!m) {
+ return null;
+ }
+ const value = Number(s);
+ if (!Number.isFinite(value)) {
+ return null;
+ }
+ const decimals = m[3] ? m[3].length : 0;
+ const exponent = m[4] ? parseInt(m[4], 10) : 0;
+ const half = 0.5 * Math.pow(10, exponent - decimals);
+ return { lo: value - half, hi: value + half, value };
+}
+
/**
* Take the comparison prefix (eq, ge, ...) off a date or number search value.
* @returns {{prefix: string, rest: string}} prefix is 'eq' when there is none
@@ -88,6 +247,14 @@ function escapeLike(value) {
return value.replace(/[\\%_]/g, (c) => '\\' + c);
}
+/**
+ * Escape a value for use in a LIKE pattern with ESCAPE '!'. MySQL treats a backslash in a
+ * string literal as an escape too, so a LIKE meant for both SQLite and MySQL uses '!'.
+ */
+function escapeLikeBang(value) {
+ return value.replace(/[!%_]/g, (c) => '!' + c);
+}
+
/**
* Split a parameter value on commas, honouring \, as an escaped comma.
*/
@@ -112,7 +279,17 @@ function splitValues(value) {
/**
* SQL comparing a stored [lo, hi) range (two column expressions) against a search
- * range, for a comparison prefix.
+ * range, for a comparison prefix. From the specification's definitions:
+ *
+ * eq the search range fully contains the resource range lo >= pLo and hi <= pHi
+ * ne it does not not (eq)
+ * gt the range above the search value overlaps hi > pHi
+ * lt the range below the search value overlaps lo < pLo
+ * ge [pLo, +infinity) overlaps hi > pLo
+ * le (-infinity, pHi) overlaps lo < pHi
+ * sa no overlap, and the resource range is above lo >= pHi
+ * eb no overlap, and the resource range is below hi <= pLo
+ * ap the ranges overlap (the caller widens the search range: approxDateRange)
*
* @param {{lo: string, hi: string}} cols - column expressions
* @param {string} prefix
@@ -135,4 +312,26 @@ function dateClause(cols, prefix, range) {
return null;
}
-module.exports = { PREFIXES, dateRange, splitPrefix, escapeLike, splitValues, dateClause };
+/**
+ * The same comparisons as dateClause, in JavaScript: whether a resource range matches a
+ * search range. For tests, and for checking values in memory.
+ */
+function rangeMatches(prefix, resource, search) {
+ switch (prefix) {
+ case 'eq': return resource.lo >= search.lo && resource.hi <= search.hi;
+ case 'ne': return !(resource.lo >= search.lo && resource.hi <= search.hi);
+ case 'gt': return resource.hi > search.hi;
+ case 'lt': return resource.lo < search.lo;
+ case 'ge': return resource.hi > search.lo;
+ case 'le': return resource.lo < search.hi;
+ case 'sa': return resource.lo >= search.hi;
+ case 'eb': return resource.hi <= search.lo;
+ case 'ap': return resource.lo < search.hi && resource.hi > search.lo;
+ }
+ return false;
+}
+
+module.exports = {
+ PREFIXES, MIN_INSTANT, MAX_INSTANT, dateRange, periodRange, approxDateRange, numberRange, splitPrefix,
+ escapeLike, escapeLikeBang, splitValues, dateClause, rangeMatches, zoneOffset, wallToInstant
+};
diff --git a/library/role.js b/library/role.js
index f5f653e2..4fc3b31a 100644
--- a/library/role.js
+++ b/library/role.js
@@ -13,15 +13,43 @@
* - master: every configured module, every background job, $closure and the syndication
* feed. The VSAC provider syncs and, after each sync, bumps a generation counter that the
* workers watch.
- * - tx-worker: the tx module only. No background jobs, no statistics database, no $closure
- * or syndication store (those requests go to the master), and the VSAC provider only
- * reads what the master's sync wrote.
+ * - tx-worker: the modules in server.cluster.workerModules - the tx module by default, and
+ * the rest module if it is listed (["tx", "rest"]). No background jobs, no statistics
+ * database, no $closure or syndication store (those requests go to the master), the VSAC
+ * provider only reads what the master's sync wrote, and the rest module's endpoints wait
+ * for the master's schema migrations and leave its jobs to the master.
*
* @module library/role
*/
const ROLES = ['master', 'tx-worker'];
+// the modules a worker can run (server.cluster.workerModules): those whose state is all in
+// files or databases every process can share. The tx module is always one of them
+const WORKER_MODULES = ['tx', 'rest'];
+const DEFAULT_WORKER_MODULES = ['tx'];
+
+/**
+ * The modules a worker runs: server.cluster.workerModules, checked.
+ * @param {Object} config
+ * @returns {string[]}
+ */
+function workerModules(config) {
+ const list = config.server && config.server.cluster && config.server.cluster.workerModules;
+ if (list === undefined || list === null) {
+ return DEFAULT_WORKER_MODULES;
+ }
+ if (!Array.isArray(list) || list.some(m => typeof m !== 'string')) {
+ throw new Error('server.cluster.workerModules must be a list of module names, e.g. ["tx", "rest"]');
+ }
+ for (const m of list) {
+ if (!WORKER_MODULES.includes(m)) {
+ throw new Error(`server.cluster.workerModules: a worker can't run the ${m} module (only ${WORKER_MODULES.join(' and ')})`);
+ }
+ }
+ return list.includes('tx') ? list : ['tx', ...list];
+}
+
/**
* An instance code goes in front of every cache-id the process issues, and a front door
* routes on it (nginx.md's map on "^tx1\."). It has to be 1-16 letters and digits: the
@@ -172,9 +200,10 @@ function applyRole(config, role) {
const interval = stats.intervalMinutes > 0 ? stats.intervalMinutes * 60 : 600;
config.stats = { ...stats, sampleSeconds: Math.min(ROLE_SAMPLE_SECONDS, interval) };
}
+ const keep = workerModules(config);
if (role.role === 'tx-worker') {
for (const [name, mod] of Object.entries(config.modules)) {
- if (name !== 'tx' && mod) {
+ if (!keep.includes(name) && mod) {
mod.enabled = false;
}
}
@@ -190,8 +219,8 @@ function describeRole(role, config) {
const code = config.modules.tx.instanceCode;
return role.role === 'master'
? `Role: master (instance code ${code}): all modules, background jobs, $closure`
- : `Role: tx-worker (instance code ${code}): the tx module only, no background jobs`;
+ : `Role: tx-worker (instance code ${code}): the ${workerModules(config).join(' and ')} module${workerModules(config).length > 1 ? 's' : ''} only, no background jobs`;
}
-module.exports = { parseRole, applyRole, describeRole, checkInstanceCode, bindAddress, connectAddress, DEFAULT_BIND_ADDRESS,
+module.exports = { parseRole, applyRole, describeRole, workerModules, WORKER_MODULES, checkInstanceCode, bindAddress, connectAddress, DEFAULT_BIND_ADDRESS,
DEFAULT_SHARED_CACHE_MAX_MB, ROLE_TRIM_ALLOCATOR, ROLE_SAMPLE_SECONDS, READY, ROLES };
diff --git a/package-lock.json b/package-lock.json
index a0c1a7df..c1011018 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -32,6 +32,7 @@
"jose": "^5.10.0",
"liquidjs": "^10.25.5",
"lusca": "^1.7.0",
+ "mysql2": "^3.24.6",
"natural": "^8.1.1",
"node-cron": "^4.6.0",
"nodemailer": "^10.2.0",
@@ -2527,7 +2528,6 @@
"version": "26.1.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.1.1.tgz",
"integrity": "sha512-nxAkRSVkN1Y0JC1W8ky/fTfkGsMmcrRsbx+3XoZE+rMOX71kLYTV7fLXpqud1GpbpP5TuffXFqfX7fH2GgZREw==",
- "devOptional": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.3.0"
@@ -3372,6 +3372,15 @@
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"license": "MIT"
},
+ "node_modules/aws-ssl-profiles": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
+ "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 6.0.0"
+ }
+ },
"node_modules/axios": {
"version": "1.20.0",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.20.0.tgz",
@@ -5451,6 +5460,15 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/generate-function": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
+ "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
+ "license": "MIT",
+ "dependencies": {
+ "is-property": "^1.0.2"
+ }
+ },
"node_modules/gensync": {
"version": "1.0.0-beta.2",
"resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz",
@@ -5992,6 +6010,12 @@
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT"
},
+ "node_modules/is-property": {
+ "version": "1.0.2",
+ "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
+ "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
+ "license": "MIT"
+ },
"node_modules/is-stream": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
@@ -7148,6 +7172,12 @@
"node": ">= 12.0.0"
}
},
+ "node_modules/long": {
+ "version": "5.3.2",
+ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
+ "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
+ "license": "Apache-2.0"
+ },
"node_modules/lru-cache": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz",
@@ -7158,6 +7188,21 @@
"yallist": "^3.0.2"
}
},
+ "node_modules/lru.min": {
+ "version": "1.1.5",
+ "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.5.tgz",
+ "integrity": "sha512-5J9ysMYUpYIg9RF2vJpy9SinEmSviFSe0GyPpCQ4L5QSkLAgeLXlTAOu2ZwWUU5m+0SBl6gUU1R1ZQB3aKypfA==",
+ "license": "MIT",
+ "engines": {
+ "bun": ">=1.0.0",
+ "deno": ">=1.30.0",
+ "node": ">=8.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wellwelwel"
+ }
+ },
"node_modules/lusca": {
"version": "1.7.0",
"resolved": "https://registry.npmjs.org/lusca/-/lusca-1.7.0.tgz",
@@ -7499,6 +7544,39 @@
"integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==",
"license": "ISC"
},
+ "node_modules/mysql2": {
+ "version": "3.24.6",
+ "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.6.tgz",
+ "integrity": "sha512-enu73KhbAua2L3dIxjc6qg6ZJ7H3pt1BImZASWNWY5xSsmJ1ZuUPULTDGXgmJbI61vb+nJAG19IZclIq19UidQ==",
+ "license": "MIT",
+ "dependencies": {
+ "aws-ssl-profiles": "^1.1.2",
+ "generate-function": "^2.3.1",
+ "iconv-lite": "^0.7.3",
+ "long": "^5.3.2",
+ "lru.min": "^1.1.4",
+ "named-placeholders": "^1.1.6",
+ "sql-escaper": "^1.5.1"
+ },
+ "engines": {
+ "node": ">= 8.0"
+ },
+ "peerDependencies": {
+ "@types/node": ">= 8"
+ }
+ },
+ "node_modules/named-placeholders": {
+ "version": "1.1.6",
+ "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz",
+ "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==",
+ "license": "MIT",
+ "dependencies": {
+ "lru.min": "^1.1.0"
+ },
+ "engines": {
+ "node": ">=8.0.0"
+ }
+ },
"node_modules/napi-build-utils": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/napi-build-utils/-/napi-build-utils-2.0.0.tgz",
@@ -9061,6 +9139,21 @@
"node": ">= 10.x"
}
},
+ "node_modules/sql-escaper": {
+ "version": "1.9.1",
+ "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.9.1.tgz",
+ "integrity": "sha512-4p522TVYaJXTbMlYgAwacjyg3EJyYe9KYWYlYJVwZG1YjtzxU5m5iSzsZoGI69Po7j3i/2tKlpZQi7uvhTL+WA==",
+ "license": "MIT",
+ "engines": {
+ "bun": ">=1.0.0",
+ "deno": ">=2.0.0",
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/mysqljs/sql-escaper?sponsor=1"
+ }
+ },
"node_modules/sqlite3": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/sqlite3/-/sqlite3-6.0.1.tgz",
@@ -9807,7 +9900,6 @@
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
- "devOptional": true,
"license": "MIT"
},
"node_modules/universalify": {
diff --git a/package.json b/package.json
index 85131c6f..f9315852 100644
--- a/package.json
+++ b/package.json
@@ -57,6 +57,7 @@
"jose": "^5.10.0",
"liquidjs": "^10.25.5",
"lusca": "^1.7.0",
+ "mysql2": "^3.24.6",
"natural": "^8.1.1",
"node-cron": "^4.6.0",
"nodemailer": "^10.2.0",
diff --git a/rest/README.md b/rest/README.md
new file mode 100644
index 00000000..7d0e1268
--- /dev/null
+++ b/rest/README.md
@@ -0,0 +1,170 @@
+# The rest module
+
+Database-backed FHIR RESTful servers inside FHIRsmith. Each endpoint has its own FHIR version,
+definitions, data and users' roles, and keeps its state in SQLite or MySQL. Processes cache
+very little: any process can serve any request, so the module runs under the cluster like the
+tx module.
+
+The design is in the design document (*FHIRsmith REST module: design*); this file is how to
+run it.
+
+## What it does
+
+- JSON only (XML gets 415 or 406)
+- read, vread, create, update, patch (JSON Patch), delete, history, search, capabilities,
+ batch and transaction, with conditional create, update, patch and delete
+- search: every parameter type and the usual modifiers and prefixes, chains and `_has` (3
+ levels), composites, `_filter`, `_list`, `_sort`, `_include` and `_revinclude` (with
+ `:iterate`), `_summary`, `_elements`, `_total`, and paging through stored results
+- `:below` and `:above` on tokens through a closure table, kept up to date with the endpoint's
+ terminology server's `$closure`; `:in` and `:not-in` through its `$expand`
+- `$meta`, `$meta-add`, `$meta-delete`, and `Patient/[id]/$everything`
+- AuditEvents for writes (and, if set, reads and failures), stored on the endpoint
+- a subscription queue (`SubscriptionQueue`), filled by every write; nothing delivers it yet
+- users and roles from the server's logins (library/auth)
+
+What search supports, parameter by parameter, is in [search.md](search.md).
+
+Not yet: XML, subscription delivery, validation on write, SMART on FHIR, asynchronous
+operations, `$lastn`, `_text` and `_content`, FHIRPath Patch, admin pages.
+
+## Configuration
+
+config.json says only where each endpoint is and which database it uses:
+
+```json
+"rest": {
+ "enabled": true,
+ "endpoints": [
+ { "path": "/fhir/r4", "fhirVersion": "4.0.1",
+ "database": { "type": "sqlite", "file": "rest/fhir-r4.db" },
+ "initialSettings": { "name": "R4 test server", "anonymous": "read" } },
+ { "path": "/fhir/r5", "fhirVersion": "5.0.0",
+ "database": { "type": "mysql", "host": "localhost", "database": "fhir_r5",
+ "user": "fhirsmith", "passwordEnv": "FHIR_R5_DB_PASSWORD" } }
+ ]
+}
+```
+
+| Setting | |
+|---|---|
+| `path` | Where the endpoint is on this server. |
+| `fhirVersion` | The FHIR version (3.0, 4.0, 4.3 or 5.0). Fixed when the database is made; a different one later is an error. |
+| `database` | `{ "type": "sqlite", "file" }` (relative to the databases folder), or `{ "type": "mysql", "host", "port", "database", "user", "passwordEnv" or "passwordFile", "connections" }`. Never a password in config.json: `passwordEnv` names an environment variable, `passwordFile` a file only the server can read. Two endpoints can't share a database. |
+| `baseUrl` | The endpoint's public URL, if it isn't `https://{hostName}{path}`: references to it are local references. |
+| `initialSettings` | Settings (below) written into a new database. A setting already in the database is never changed from here: the log warns at start-up when the two differ. |
+| `types` | Per-type settings (below) for types not in the database yet. |
+| `modules.rest.packageServers` | The package servers definitions are fetched from (packages2.fhir.org, then packages.fhir.org). |
+
+The database's tables are made, and later brought up to date, when the server starts (on the
+master, under a lock). A MySQL database must exist, with a user that can create tables in it,
+`utf8mb4`.
+
+## Settings
+
+Everything else about an endpoint is in its own database: the `Config` table (`Name`, `Value`)
+and, per resource type, `Types.Settings` (JSON). There are no admin pages yet: change them in
+the database, and bump the `generation` row in `Config` (every process reloads within a second
+when it changes).
+
+| `Config` | Default | |
+|---|---|---|
+| `name`, `description` | | For the CapabilityStatement. |
+| `packages` | `[]` | IG packages (`id#version`, JSON list) whose search parameters and compartments are loaded, after the core package. |
+| `idStrategy` | `key` | Server-assigned ids: `key` (the resource's database key: short) or `uuid`. |
+| `createOnUpdate` | true | PUT to a new id creates. |
+| `checkReferences` | true | A write whose references to this endpoint don't resolve gets 422. |
+| `txServer` | | The terminology server for `:in`, `:not-in` and the closure: a path on this server (the tx module's endpoint, in process) or a URL. |
+| `audit` | `writes` | AuditEvents: `off`, `writes`, or `all` (reads and failures too). |
+| `defaultCount`, `maxCount` | 50, 500 | Page sizes. |
+| `searchMaxResults` | 20000 | The most results a search keeps for paging. |
+| `searchKeepMinutes` | 30 | How long stored results are kept. |
+| `timeZone` | the server's | For dates without a zone (an IANA name). |
+| `compress` | true | Resources are stored gzipped. |
+| `transactionMaxEntries` | 1000 | The biggest transaction. |
+| `anonymous` | `none` | `read`: anyone can read (a public server); `write`: anyone can read and write (a sandbox). |
+| `customSearchParameters` | false | SearchParameter resources stored on the endpoint are used too. |
+| `conditionalDeleteMax` | 1 | The most resources a conditional delete deletes. |
+
+| `Types.Settings` | Default | |
+|---|---|---|
+| `versionAware` | false | Updates and patches need `If-Match`. |
+| `interactions` | all | The interactions allowed: `read`, `vread`, `update`, `patch`, `delete`, `history-instance`, `history-type`, `create`, `search-type`. |
+| `conditionalCreate`, `conditionalUpdate`, `conditionalDelete` | true | |
+
+`Types.Supported` 0 takes a type off the endpoint.
+
+## Transactions
+
+A transaction is all or nothing: every entry is written in one database transaction, and any
+failure leaves the database as it was, with the failing entry's OperationOutcome (naming the
+entry). Before anything is written:
+
+- every write entry is given the one resource it changes. A POST gets a new id; a conditional
+ create, update, patch or delete is searched once, here. **A resource may be changed by only
+ one entry**: two that change the same one (directly, or through what a conditional resolves
+ to) fail the transaction, with 400. So do two conditional creates with the same criteria
+- conditional references (`Patient?identifier=x`) are searched: exactly one match, else 412
+- every write entry's fullUrl (a `urn:uuid:`, or an absolute URL) is mapped to its resource,
+ and references to it are rewritten wherever they are the whole value of an element, and in
+ narratives in `` and ` | A problem list with hypertension | Problem List (LOINC|11450-4) - must be asked/known, must have supporting entries | Code is SNOMED CT|38341003 | '); expect(page.text).toContain('Expectation | Section | Entry | '); expect(page.text).toContain('Hypertension is active | Conditions where Code is SNOMED CT|38341003 | .all(clinicalStatus.coding.code = 'active') | ');
@@ -2922,17 +2930,19 @@ describe('clinical profiles', () => {
const listPage = await request(app).get('/ips/StructureDefinition').set('Accept', 'text/html');
expect(listPage.text).toContain('Cardiology referral');
expect(listPage.text).not.toContain('New profile');
- // the administrator's editor gets the shapes
- const editor = await agent.get(`/ips/StructureDefinition/${id}/edit`).set('Accept', 'text/html');
+ // the administrator's page gets the shapes; there is no full editor (an old link to it lands on the page)
+ expect((await agent.get(`/ips/StructureDefinition/${id}/edit`)).headers.location).toBe(`/ips/StructureDefinition/${id}`);
+ const editor = await agent.get(`/ips/StructureDefinition/${id}`).set('Accept', 'text/html');
+ expect(editor.text).not.toContain('Edit all');
const cfg = JSON.parse(/window\.IPS_PROFILE = (.*?);<\/script>/.exec(editor.text)[1]);
- expect(cfg.profile.constraints[0]).toMatchObject({ key: 'cp-1', shape: { section: { system: L, code: '11450-4', min: 1, max: '*' }, entry: { system: S, code: '38341003', min: null, max: null } } });
+ expect(cfg.profile.constraints[0]).toMatchObject({ key: 'cp-1', shape: { section: { system: L, code: '11450-4', checks: ['isKnown', 'hasData'] }, entry: { system: S, code: '38341003', min: null, max: null } } });
expect(cfg.profile.constraints[1].shape).toBeNull();
expect(cfg.profile.constraints[1].rshape).toBeNull();
expect(cfg.profile.constraints[2].rshape).toEqual({ type: 'Condition', system: S, code: '38341003', rest: ".all(clinicalStatus.coding.code = 'active')" });
expect(cfg.parts.map(p => p[0])).toEqual(['section', 'resource', 'other']);
expect(cfg.resourceTypes).toContain('Condition');
expect(cfg.sections[0]).toEqual({ code: '11450-4', title: 'Problem List' });
- expect(cfg.urls).toEqual({ save: `/ips/StructureDefinition/${id}`, lookup: '/ips/lookup', lookupVs: '/ips/lookup-vs', back: `/ips/StructureDefinition/${id}` });
+ expect(cfg.urls).toEqual({ constraint: `/ips/StructureDefinition/${id}/constraint`, guide: `/ips/StructureDefinition/${id}/guide`, lookup: '/ips/lookup', lookupVs: '/ips/lookup-vs' });
// an edit keeps the url and the kept keys
const saved = await send(`/ips/StructureDefinition/${id}`, { title: 'Cardiology referral v2', constraints: [{ key: 'cp-2', human: 'At least two sections', expression: 'Bundle.entry.count() >= 2' }, { human: 'Medications', expression: `Bundle.section('${L}', '10160-0', 1, 1).exists()` }] });
expect(saved.status).toBe(200);
@@ -2971,29 +2981,29 @@ describe('clinical profiles', () => {
test('the administrator adds, edits and deletes a rule at a time, on the profile\'s page', async () => {
const { agent, send } = await asAdmin();
const vs = 'http://example.org/ValueSet/heart';
- const made = await send('/ips/StructureDefinition', { title: 'Rows', constraints: [{ human: 'Problems', expression: `Bundle.section('${L}', '11450-4', 1, 1).exists()` }, { human: 'Two entries', expression: 'Bundle.entry.count() >= 2' }] });
+ const made = await send('/ips/StructureDefinition', { title: 'Rows', constraints: [{ human: 'Problems', expression: `Bundle.section('${L}', '11450-4').isKnown()` }, { human: 'Two entries', expression: 'Bundle.entry.count() >= 2' }] });
const id = made.body.id;
const at = `/ips/StructureDefinition/${id}`;
// the same page as a visitor's, with the rows' actions and the script
const page = await agent.get(at).set('Accept', 'text/html');
- expect(page.text).toContain('Problems | Problem List (LOINC|11450-4) | '); + expect(page.text).toContain(' | Problems | Problem List (LOINC|11450-4) - must be asked/known | '); expect(page.text).toContain(`action="${at}/constraint/cp-1/delete"`); expect(page.text).toContain(' |