From b85447b11b6235c18fb3f2db4bccd63602930041 Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Sun, 22 Nov 2026 19:53:09 +1100 Subject: [PATCH 1/3] add Patient comments to IPS --- ips/OperationDefinition-ips-document.json | 69 +++++ ips/export.js | 286 ++++++++++++++++++++ ips/ips.js | 310 ++++++++++++++++++++-- ips/patient-comments.js | 171 ++++++++++++ ips/pipeline.js | 122 +++++---- ips/readme.md | 35 ++- ips/render.js | 151 +++++++++-- ips/share.js | 47 +++- ips/signatures.js | 7 + ips/store.js | 28 ++ 10 files changed, 1134 insertions(+), 92 deletions(-) create mode 100644 ips/OperationDefinition-ips-document.json create mode 100644 ips/export.js create mode 100644 ips/patient-comments.js diff --git a/ips/OperationDefinition-ips-document.json b/ips/OperationDefinition-ips-document.json new file mode 100644 index 00000000..57987b29 --- /dev/null +++ b/ips/OperationDefinition-ips-document.json @@ -0,0 +1,69 @@ +{ + "resourceType": "OperationDefinition", + "id": "ips-document", + "url": "https://github.com/HealthIntersections/FHIRsmith/blob/main/ips/OperationDefinition-ips-document.json", + "version": "1.0.0", + "name": "IpsDocument", + "title": "Get a stored IPS document, prepared for sharing", + "status": "active", + "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.", + "affectsState": false, + "code": "document", + "resource": ["Bundle"], + "system": false, + "type": false, + "instance": true, + "parameter": [ + { + "name": "source", + "use": "in", + "min": 0, + "max": "1", + "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": "user-sign", + "use": "in", + "min": 0, + "max": "1", + "documentation": "Sign as the user: the owner of the API token in the Authorization header (Bearer). 401 if there is no API token, 409 if the user has no key pair the server can sign with (made on their keys page)", + "type": "boolean" + }, + { + "name": "system-sign", + "use": "in", + "min": 0, + "max": "1", + "documentation": "Sign as the system (this server). The system signs for any one address no more often than the server's configured interval: 429 if it is too soon", + "type": "boolean" + }, + { + "name": "patient-notes", + "use": "in", + "min": 0, + "max": "1", + "documentation": "Include the patient's comments, as the Composition's first section (LOINC 51855-5, title 'Patient's Comments', the patient as author, the comments as narrative with status additional), added after signing. If the document has no patient comments, nothing is added and this is not an error", + "type": "boolean" + }, + { + "name": "regenerate-narrative", + "use": "in", + "min": 0, + "max": "1", + "documentation": "Regenerate the narrative of the Composition and its sections with the server's IPS presenter, as the narrative tab's Generated view shows it, before any signing", + "type": "boolean" + }, + { + "name": "return", + "use": "out", + "min": 1, + "max": "1", + "documentation": "The document (a Bundle of type document). For the other formats, the response body is the ZIP, the PDF, or the QR code's PNG, not a Parameters resource", + "type": "Bundle" + } + ] +} diff --git a/ips/export.js b/ips/export.js new file mode 100644 index 00000000..9aea0d77 --- /dev/null +++ b/ips/export.js @@ -0,0 +1,286 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * A document as a ZIP or a PDF, made on the server - for the API ($document), where the web + * page makes them in the browser (doc-actions.js download). The same content: the ZIP holds + * the document as {name}.json; the PDF has the title, the patient, the date and each section's + * narrative (doc-actions.js defaultHtml), with the document attached as {name}.json. + * + * The PDF is laid out as text with pdf-lib's standard fonts, not rendered from the HTML: tables + * become rows of cells, images are left out, and characters the standard fonts don't have + * (outside Windows-1252) show as '?'. + */ + +const zlib = require('zlib'); +const parse5 = require('parse5'); +const { PDFDocument, StandardFonts, rgb } = require('./vendor/pdf-lib.min.js'); + +// ---- ZIP -------------------------------------------------------------------------------------- + +/** + * A ZIP file of the given files (deflated; names in UTF-8). + * @param {Array<{name: string, data: Buffer|string}>} files + * @param {Date} [when] - the files' modification time + * @returns {Buffer} + */ +function zip(files, when = new Date()) { + const dosTime = (when.getHours() << 11) | (when.getMinutes() << 5) | Math.floor(when.getSeconds() / 2); + const dosDate = ((Math.max(when.getFullYear(), 1980) - 1980) << 9) | ((when.getMonth() + 1) << 5) | when.getDate(); + const locals = []; + const centrals = []; + let offset = 0; + for (const f of files) { + const name = Buffer.from(f.name, 'utf8'); + const data = Buffer.isBuffer(f.data) ? f.data : Buffer.from(f.data, 'utf8'); + const packed = zlib.deflateRawSync(data); + const crc = zlib.crc32(data); + const local = Buffer.alloc(30); + local.writeUInt32LE(0x04034b50, 0); + local.writeUInt16LE(20, 4); // version needed + local.writeUInt16LE(0x0800, 6); // UTF-8 names + local.writeUInt16LE(8, 8); // deflate + local.writeUInt16LE(dosTime, 10); + local.writeUInt16LE(dosDate, 12); + local.writeUInt32LE(crc, 14); + local.writeUInt32LE(packed.length, 18); + local.writeUInt32LE(data.length, 22); + local.writeUInt16LE(name.length, 26); + local.writeUInt16LE(0, 28); + const central = Buffer.alloc(46); + central.writeUInt32LE(0x02014b50, 0); + central.writeUInt16LE(20, 4); // made by + central.writeUInt16LE(20, 6); + central.writeUInt16LE(0x0800, 8); + central.writeUInt16LE(8, 10); + central.writeUInt16LE(dosTime, 12); + central.writeUInt16LE(dosDate, 14); + central.writeUInt32LE(crc, 16); + central.writeUInt32LE(packed.length, 20); + central.writeUInt32LE(data.length, 24); + central.writeUInt16LE(name.length, 28); + central.writeUInt32LE(offset, 42); + locals.push(local, name, packed); + centrals.push(central, name); + offset += local.length + name.length + packed.length; + } + const dir = Buffer.concat(centrals); + const end = Buffer.alloc(22); + end.writeUInt32LE(0x06054b50, 0); + end.writeUInt16LE(files.length, 8); + end.writeUInt16LE(files.length, 10); + end.writeUInt32LE(dir.length, 12); + end.writeUInt32LE(offset, 16); + return Buffer.concat([...locals, dir, end]); +} + +// ---- PDF -------------------------------------------------------------------------------------- + +const isObject = (x) => x !== null && typeof x === 'object' && !Array.isArray(x); +const str = (x) => (typeof x === 'string' ? x : ''); + +// as doc-actions.js resolve +function resolve(bundle, ref) { + const r = ref && typeof ref.reference === 'string' ? ref.reference : null; + if (!r) { + return null; + } + for (const e of bundle.entry || []) { + const res = e?.resource; + if (res && (e.fullUrl === r || `${res.resourceType}/${res.id}` === r || (e.fullUrl && e.fullUrl.slice(-r.length - 1) === '/' + r))) { + return res; + } + } + return null; +} + +function nameOf(p) { + const n = p && Array.isArray(p.name) ? p.name[0] : null; + if (!n) { + return ''; + } + return n.text || `${(n.given || []).join(' ')} ${n.family || ''}`.trim(); +} + +const BLOCKS = new Set(['p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'ul', 'ol', 'li', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'pre', 'blockquote', 'dl', 'dt', 'dd', 'hr', 'caption']); +const SKIP = new Set(['script', 'style', 'img', 'head', 'title']); + +/** + * A narrative (XHTML) as lines of text: blocks are lines, list items are bulleted, a table row + * is its cells joined with ' | ', headings are bold. + * @returns {Array<{text: string, bold: boolean}>} + */ +function narrativeLines(div) { + const lines = []; + let current = ''; + let bold = false; + const flush = () => { + const t = current.replace(/\s+/g, ' ').trim(); + if (t) { + lines.push({ text: t, bold }); + } + current = ''; + bold = false; + }; + const walk = (node) => { + const tag = node.tagName; + if (tag && SKIP.has(tag)) { + return; + } + if (node.nodeName === '#text') { + current += node.value; + return; + } + if (tag === 'br') { + flush(); + return; + } + if (tag === 'tr') { + flush(); + const cells = (node.childNodes || []).filter(c => c.tagName === 'td' || c.tagName === 'th'); + const text = cells.map(c => { + const inner = narrativeLines(parse5.serializeOuter(c)).map(l => l.text).join(' '); + return inner; + }).join(' | '); + lines.push({ text: text.replace(/\s+/g, ' ').trim(), bold: cells.length > 0 && cells.every(c => c.tagName === 'th') }); + return; + } + const block = tag && BLOCKS.has(tag); + if (block) { + flush(); + } + if (tag === 'li') { + current = '• '; + } + if (/^h[1-6]$/.test(tag || '')) { + bold = true; + } + for (const c of node.childNodes || []) { + walk(c); + } + if (block) { + flush(); + } + }; + for (const c of parse5.parseFragment(str(div)).childNodes) { + walk(c); + } + flush(); + return lines.filter(l => l.text); +} + +/** What the PDF says, as doc-actions.js defaultHtml has it. @returns {Array<{text, kind}>} kind: h1, h2, p, i */ +function pdfContent(bundle) { + const comp = bundle?.entry?.[0]?.resource; + if (!isObject(comp)) { + return [{ text: 'Patient Summary', kind: 'h1' }]; + } + const out = [{ text: comp.title || 'Patient Summary', kind: 'h1' }]; + const patient = resolve(bundle, comp.subject); + if (patient) { + out.push({ text: nameOf(patient) + (patient.birthDate ? `, born ${patient.birthDate}` : '') + (patient.gender ? `, ${patient.gender}` : ''), kind: 'b' }); + } + if (comp.date) { + out.push({ text: `Date: ${comp.date}`, kind: 'p' }); + } + for (const s of comp.section || []) { + if (!isObject(s)) { + continue; + } + out.push({ text: s.title || s.code?.text || 'Section', kind: 'h2' }); + if (s.text && s.text.div) { + for (const l of narrativeLines(s.text.div)) { + out.push({ text: l.text, kind: l.bold ? 'b' : 'p' }); + } + } else if (s.emptyReason) { + out.push({ text: s.emptyReason.coding?.[0]?.display || s.emptyReason.text || 'Empty', kind: 'i' }); + } + } + return out; +} + +/** + * The document as a PDF (A4), with the document attached as {name}.json. + * @param {Object} bundle - the document + * @param {string} json - the document as text (what is attached) + * @param {string} name - the attachment's name, without .json + * @returns {Promise} + */ +async function pdf(bundle, json, name) { + const doc = await PDFDocument.create(); + const fonts = { + p: await doc.embedFont(StandardFonts.Helvetica), + b: await doc.embedFont(StandardFonts.HelveticaBold), + i: await doc.embedFont(StandardFonts.HelveticaOblique) + }; + const SIZES = { h1: 18, h2: 13, b: 10, p: 10, i: 10 }; + const FONT = { h1: 'b', h2: 'b', b: 'b', p: 'p', i: 'i' }; + // what the standard fonts can show (Windows-1252): anything else is '?' + const known = new Set(fonts.p.getCharacterSet()); + const clean = (t) => Array.from(t.normalize('NFC').replace(/[\t\r\n]/g, ' ')).map(ch => (known.has(ch.codePointAt(0)) ? ch : '?')).join(''); + const W = 595.28; + const H = 841.89; + const M = 40; + let page = doc.addPage([W, H]); + let y = H - M; + const newPage = () => { + page = doc.addPage([W, H]); + y = H - M; + }; + // split a line into lines that fit the width (a word too long is broken) + const wrap = (text, font, size) => { + const width = W - 2 * M; + const out = []; + let line = ''; + for (const word of text.split(' ')) { + const tryLine = line ? `${line} ${word}` : word; + if (font.widthOfTextAtSize(tryLine, size) <= width) { + line = tryLine; + continue; + } + if (line) { + out.push(line); + } + let w = word; + while (font.widthOfTextAtSize(w, size) > width) { + let n = w.length - 1; + while (n > 1 && font.widthOfTextAtSize(w.substring(0, n), size) > width) { + n--; + } + out.push(w.substring(0, n)); + w = w.substring(n); + } + line = w; + } + if (line) { + out.push(line); + } + return out; + }; + for (const item of pdfContent(bundle)) { + const size = SIZES[item.kind]; + const font = fonts[FONT[item.kind]]; + if (item.kind === 'h2') { + y -= 8; + } + for (const line of wrap(clean(item.text), font, size)) { + if (y - size < M) { + newPage(); + } + y -= size * 1.3; + page.drawText(line, { x: M, y, size, font, color: rgb(0, 0, 0) }); + } + y -= item.kind === 'h1' ? 8 : 3; + } + const title = pdfContent(bundle)[0].text; + doc.setTitle(title); + doc.setProducer('FHIRsmith'); + await doc.attach(Buffer.from(json, 'utf8'), `${name}.json`, { mimeType: 'application/fhir+json', description: 'IPS Document' }); + // without object streams: plainer, and what is attached can be seen in the file + return Buffer.from(await doc.save({ useObjectStreams: false })); +} + +module.exports = { zip, pdf, pdfContent, narrativeLines }; diff --git a/ips/ips.js b/ips/ips.js index 7af84ca3..243df3ba 100644 --- a/ips/ips.js +++ b/ips/ips.js @@ -66,8 +66,10 @@ const { IpsStore } = require('./store'); const patients = require('./patients'); const { parseSearch, listQueryToSearch, capabilitySearchParams, compositionOf, patientOf } = require('./search'); const render = require('./render'); +const patientComments = require('./patient-comments'); +const exporter = require('./export'); const { TxClient } = require('./tx-client'); -const { STEPS, stripChecks, withTimeout } = require('./pipeline'); +const { STEPS, stripChecks, withTimeout, generateNarrative } = require('./pipeline'); const signatures = require('./signatures'); const { KeyStoreKeyProvider } = require('./signature-keys'); const keystore = require('../library/keystore'); @@ -77,7 +79,7 @@ const { Reports, SOURCES: REPORT_SOURCES } = require('./reports'); const MAX_CACHED_EXTENSIONS = 5000; const { IpsValueSets } = require('./ips-valuesets'); const aiClient = require('./ai-client'); -const { ShlClient } = require('./share'); +const { ShlClient, qrPng } = require('./share'); const { ShlViewer, Trace } = require('./viewer'); const composer = require('./composer'); const editorSchema = require('./editor-schema'); @@ -95,6 +97,103 @@ const SIGN_TIMEOUT_MS = 30000; function isOn(v) { return v === true || v === '1' || v === 'on' || v === 'true'; } + +// ---- $document: its parameters and formats ---- + +// 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' +}; +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' +}; +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' }; + +/** + * $document's parameters: from the query (GET), or a Parameters resource (POST). + * @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 given = []; + if (req.method === 'POST') { + let b = req.body; + // a parser in front of the module may have left it as it came + if (Buffer.isBuffer(b)) { + try { + b = JSON.parse(b.toString('utf8')); + } catch { + b = null; + } + } + if (!b || typeof b !== 'object' || b.resourceType !== 'Parameters') { + out.problems.push('POST $document with a Parameters resource (application/fhir+json)'); + return out; + } + for (const prm of Array.isArray(b.parameter) ? b.parameter : []) { + const v = prm?.valueBoolean !== undefined ? prm.valueBoolean : prm?.valueCode !== undefined ? prm.valueCode : prm?.valueString; + given.push([prm?.name, v]); + } + } else { + for (const [k, v] of Object.entries(req.query || {})) { + if (k !== '_format') { + given.push([k, Array.isArray(v) ? v[v.length - 1] : v]); + } + } + } + for (const [k, v] of given) { + if (k === 'source') { + if (v === 'original' || v === 'modified') { + out.source = v; + } else { + out.problems.push(`source is original or modified, not '${v}'`); + } + } else if (DOCUMENT_BOOLEANS[k]) { + if (v === true || v === 'true') { + out[DOCUMENT_BOOLEANS[k]] = true; + } else if (!(v === false || v === 'false')) { + 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(', ')})`); + } + } + return out; +} + +/** What $document should give: _format (a short name or mime type), else Accept (by preference). @returns {string|null} */ +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); + } + const accept = req.get('Accept'); + if (!accept) { + return 'json'; + } + const wanted = accept.split(',').map((part, i) => { + const [type, ...params] = part.trim().toLowerCase().split(';').map(x => x.trim()); + const q = params.find(x => x.startsWith('q=')); + return { type, q: q ? Number(q.substring(2)) : 1, i }; + }).filter(w => w.q > 0).sort((a, b) => b.q - a.q || a.i - b.i); + for (const w of wanted) { + if (DOCUMENT_MIME[w.type]) { + return DOCUMENT_MIME[w.type]; + } + } + return null; +} const DEFAULT_MAX_SIZE = 10 * 1024 * 1024; const DEFAULT_INTERVAL_SECONDS = 5; // a terminology server on this server that isn't there: how often to look again, and how @@ -712,6 +811,17 @@ class IpsModule { next(); }; + // anyone logged in + const loggedIn = (req, res, next) => { + auth.denyFraming(res); + const user = this.currentUser(req); + if (!user) { + return res.redirect(auth.loginUrl(req)); + } + req.user = user; + next(); + }; + r.get('/editor.js', scripts.handler('editor.js')); r.get('/:code', project, ...this.web, h('list', (req, res) => this.htmlList(req, res))); r.get('/:code/metadata', project, h('metadata', (req, res) => this.metadata(req, res))); @@ -772,6 +882,12 @@ class IpsModule { // a signed copy of the document (the original, or the modified copy), for the source view's downloads r.post('/:code/Bundle/:id/signed', project, this.sameOrigin, ...posting, this.session, express.json({ limit: '16kb' }), auth.csrfIfLoggedIn, h('signed', (req, res) => this.signed(req, res))); + // the patient's comment on the document: anyone logged in can write it + r.post('/:code/Bundle/:id/comment', project, this.sameOrigin, this.session, this.form, this.csrf, loggedIn, h('comment', (req, res) => this.savePatientComment(req, res))); + // $document: the document as the source view's banner gives it, on the API (same rate limit as sharing) + const parameters = express.json({ type: ['application/fhir+json', 'application/json'], limit: '64kb' }); + r.get('/:code/Bundle/:id/\\$document', project, ...posting, h('document', (req, res) => this.documentOperation(req, res))); + r.post('/:code/Bundle/:id/\\$document', project, ...posting, parameters, h('document', (req, res) => this.documentOperation(req, res))); r.post('/:code/Bundle/:id/delete', project, this.sameOrigin, this.session, this.form, this.csrf, manager, h('delete', (req, res) => { const id = docId(req.params.id); if (!this.store.delete(id, req.project.id)) { @@ -1560,27 +1676,26 @@ class IpsModule { if (!doc) { return fail(409, `Document ${id} has not been processed yet, so there is no modified copy to share`); } - const label = row.patient_name ? `Patient Health Document for ${row.patient_name}` : 'Patient Health Document'; - // signed, if the user asked (the source view's Sign choices) - const wanted = { user: isOn(req.body.signUser), system: isOn(req.body.signSystem) }; + // signed, and with the patient's comments, if the user asked (the source view's choices) + const wanted = { user: isOn(req.body.signUser), system: isOn(req.body.signSystem), comments: isOn(req.body.comments), narrative: isOn(req.body.narrative) }; let shared = doc; - if (wanted.user || wanted.system) { + if (wanted.user || wanted.system || wanted.comments || wanted.narrative) { try { - shared = await this.signedCopy(req, doc, wanted); + shared = await this.preparedCopy(req, row, doc, wanted); } catch (e) { return fail(e.status || 500, e.message); } } let out; try { - // the QR opens this server's viewer, unless the configuration names another - out = await this.shl.share(shared, { kind, host: req.get('host'), label, viewer: this.viewer ? this.viewerUrl(req) : undefined }); + out = await this.shareCopy(req, row, shared, kind); out.source = source; } catch (e) { this.log.error(`IPS module: document ${id} could not be shared as ${kind}: ${e.message}`); return fail(502, e.message); } - this.log.info(`IPS module: document ${id} in '${req.project.code}' shared (${source}${shared !== doc ? ', signed' : ''}) as ${kind.toUpperCase()} (${out.bytes} bytes, until ${out.expires})`); + const how = [wanted.narrative ? 'narrative regenerated' : null, wanted.user || wanted.system ? 'signed' : null, wanted.comments ? 'with patient comments' : null].filter(Boolean); + this.log.info(`IPS module: document ${id} in '${req.project.code}' shared (${[source, ...how].join(', ')}) as ${kind.toUpperCase()} (${out.bytes} bytes, until ${out.expires})`); if (json) { return res.json(out); } @@ -1588,11 +1703,96 @@ class IpsModule { render.renderShare(req.project, row, out, this.ctx(req, res)), Date.now(), req); } + /** Share a copy of a document as an SHL or VHL (the shl module): {kind, link, qr (SVG), text, expires, bytes} */ + async shareCopy(req, row, doc, kind) { + const label = row.patient_name ? `Patient Health Document for ${row.patient_name}` : 'Patient Health Document'; + // the QR opens this server's viewer, unless the configuration names another + return this.shl.share(doc, { kind, host: req.get('host'), label, viewer: this.viewer ? this.viewerUrl(req) : undefined }); + } + + // ---- $document ---- + + /** + * $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. + * Its OperationDefinition is ips/OperationDefinition-ips-document.json. + */ + async documentOperation(req, res) { + const id = docId(req.params.id); + const row = this.store.read(id, req.project.id); + if (!row) { + return this.sendOutcome(res, 404, 'not-found', `No Bundle with id '${req.params.id}'`); + } + const p = documentParameters(req); + if (p.problems.length > 0) { + return this.sendOutcome(res, 400, 'invalid', p.problems); + } + const format = 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')}`); + } + const modified = p.source === 'modified'; + const doc = modified ? row.analysed : row.bundle; + if (!doc) { + return this.sendOutcome(res, 409, 'conflict', `Document ${id} has not been processed yet, so there is no modified copy`); + } + if ((format === 'shl' || format === 'vhl') && !this.shl) { + return this.sendOutcome(res, 404, 'not-supported', 'Sharing is not configured on this server (modules.ips.shl)'); + } + // on the API, the user who signs is the owner of an API token: never a session cookie + let principal = null; + if (p.userSign) { + const who = await auth.principal(req); + principal = who && who.via === 'token' ? who : null; + } + const wanted = { user: p.userSign, system: p.systemSign, comments: p.patientNotes, commentsIfAny: true, narrative: p.regenerateNarrative, principal }; + let out = doc; + if (wanted.user || wanted.system || wanted.comments || wanted.narrative) { + try { + out = await this.preparedCopy(req, row, doc, wanted); + } catch (e) { + const status = e.status || 500; + return this.sendOutcome(res, status, OUTCOME_CODES[status] || 'exception', e.message); + } + } + const signed = wanted.user || wanted.system; + const name = `ips-${req.project.code}-${row.id}${modified ? '-modified' : ''}${signed ? '-signed' : ''}`; + const how = [modified ? 'modified' : 'original', wanted.narrative ? 'narrative regenerated' : null, signed ? 'signed' : null, wanted.comments ? 'patient notes' : null].filter(Boolean).join(', '); + this.log.info(`IPS module: $document on ${row.id} in '${req.project.code}' as ${format} (${how})`); + res.set('Cache-Control', 'no-store'); + if (format === 'json') { + return this.sendJson(res, 200, out); + } + const json = JSON.stringify(out, null, 2); + if (format === 'zip') { + res.set('Content-Disposition', `attachment; filename="${name}.zip"`); + return res.status(200).type('application/zip').send(exporter.zip([{ name: `${name}.json`, data: json }])); + } + if (format === 'pdf') { + res.set('Content-Disposition', `attachment; filename="${name}.pdf"`); + return res.status(200).type('application/pdf').send(await exporter.pdf(out, json, name)); + } + // shl, vhl: the QR code as a PNG; what it carries, and until when, in headers + let shared; + try { + shared = await this.shareCopy(req, row, out, format); + } catch (e) { + this.log.error(`IPS module: $document on ${row.id} could not be shared as ${format}: ${e.message}`); + return this.sendOutcome(res, 502, 'transient', e.message); + } + res.set('X-Health-Link', shared.text); + res.set('X-Health-Link-Manifest', shared.link); + res.set('X-Health-Link-Expires', shared.expires); + return res.status(200).type('image/png').send(qrPng(shared.text)); + } + // ---- signing ---- /** - * A signed copy of a document: {source: 'original' | 'modified', user: bool, system: bool} - * -> the signed document (JSON). Not kept. + * A copy of a document as the source view's choices ask: {source: 'original' | 'modified', + * user: bool, system: bool, comments: bool, narrative: bool} -> the document (JSON), with the + * narrative regenerated, signed, and/or with the patient's comments (preparedCopy). Not kept. */ async signed(req, res) { const id = docId(req.params.id); @@ -1606,21 +1806,65 @@ class IpsModule { if (!doc) { return res.status(409).json({ error: `Document ${id} has not been processed yet, so there is no modified copy to sign` }); } - const wanted = { user: b.user === true, system: b.system === true }; - if (!wanted.user && !wanted.system) { - return res.status(400).json({ error: 'Say who signs: the user, the system, or both' }); + const wanted = { user: b.user === true, system: b.system === true, comments: b.comments === true, narrative: b.narrative === true }; + if (!wanted.user && !wanted.system && !wanted.comments && !wanted.narrative) { + return res.status(400).json({ error: 'Say who signs (the user, the system, or both), or ask for the patient\'s comments, or the narrative regenerated' }); } let signed; try { - signed = await this.signedCopy(req, doc, wanted); + signed = await this.preparedCopy(req, row, doc, wanted); } catch (e) { return res.status(e.status || 500).json({ error: e.message }); } - this.log.info(`IPS module: document ${id} in '${req.project.code}' signed (${modified ? 'modified' : 'original'}) by ${[wanted.user ? 'the user' : null, wanted.system ? 'the system' : null].filter(Boolean).join(' and ')}`); + const signers = [wanted.user ? 'the user' : null, wanted.system ? 'the system' : null].filter(Boolean); + this.log.info(`IPS module: document ${id} in '${req.project.code}' copied (${modified ? 'modified' : 'original'})` + (wanted.narrative ? ', narrative regenerated' : '') + + (signers.length ? `, signed by ${signers.join(' and ')}` : '') + (wanted.comments ? ', with the patient\'s comments' : '')); res.set('Cache-Control', 'no-store'); return this.sendJson(res, 200, signed); } + /** + * A copy of a document for download or sharing, as the source view's choices ask, in this order: + * with the patient's comments (wanted.comments), any patient notes section (LOINC 51855-5) the + * document has is removed; the narrative is regenerated (wanted.narrative), as the narrative step + * does it; it is signed (wanted.user, wanted.system: signedCopy); then the comments go in as the + * first section - after signing, so they are not signed. Throws an error with a status as + * signedCopy does, 409 when comments are asked for and there are none (unless wanted.commentsIfAny: + * then there are none to add), and 422 when the narrative can't be generated. wanted.principal: + * who signs as the user (signedCopy) + */ + async preparedCopy(req, row, doc, wanted) { + let comment = null; + if (wanted.comments) { + comment = this.store.patientComment(row.id); + if (!comment && !wanted.commentsIfAny) { + throw Object.assign(new Error(`Document ${row.id} has no patient comments to include`), { status: 409 }); + } + if (comment) { + doc = patientComments.removePatientNotes(doc); + } + } + if (wanted.narrative) { + doc = structuredClone(doc); + try { + await generateNarrative(doc, this); + } catch (e) { + throw Object.assign(new Error(`The narrative could not be generated: ${e.message}`), { status: 422 }); + } + } + if (wanted.user || wanted.system) { + doc = await this.signedCopy(req, doc, wanted); + } + if (comment) { + try { + doc = patientComments.addPatientComments(doc, comment.markdown); + } catch (e) { + throw Object.assign(new Error(e.message), { status: 422 }); + } + } + return doc; + } + /** * Who can sign the documents a request's page shows (the source view's Sign choices): the * logged in user with a key pair of a type signatures.js can use, and the system with one. @@ -1672,10 +1916,11 @@ class IpsModule { const purpose = 'ips:sign-document'; let user = null; let system = null; - const me = wanted.user ? auth.currentUser(req) : null; + // the user: the session's (the web page), or the one the API names (wanted.principal: the owner of an API token, or null) + const me = wanted.user ? (wanted.principal !== undefined ? wanted.principal : auth.currentUser(req)) : null; if (wanted.user) { if (!me) { - throw err(401, 'Log in to sign as yourself'); + throw err(401, wanted.principal !== undefined ? 'user-sign needs an API token (Authorization: Bearer ...) for the user who signs' : 'Log in to sign as yourself'); } const loaded = keystore.loadPrivateKey({ owner: me.id, types, purpose, actor: me.id }); if (!loaded) { @@ -2223,7 +2468,7 @@ class IpsModule { return res.json(list.map(np => ({ jurisdiction: np.jurisdiction, packageId: np.packageId, version: np.version, url: np.url, ...(np.snomedEdition ? { snomedEdition: np.snomedEdition } : {}) }))); } - this.sendHtml(res, 'National Profiles', render.renderNationalProfiles(list, this.ctx(req, res), message), Date.now(), req); + this.sendHtml(res, 'Jurisdictional Profiles', render.renderNationalProfiles(list, this.ctx(req, res), message), Date.now(), req); } /** Add (id null) or change a national profile, from the form: jurisdiction, packageId, version, url, snomedEdition (optional). */ @@ -2790,6 +3035,7 @@ class IpsModule { return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(`No document with id '${req.params.id}'`), 404); } const { view, narrative, source } = render.viewOf(req.query); + row.comment = this.store.patientComment(row.id); row.results = {}; for (const step of this.steps) { row.results[step.name] = this.store.readResult(row.id, step.name); @@ -2802,6 +3048,7 @@ class IpsModule { problemsOnly: req.query.problems === '1', narrative, source, + saved: req.query.saved === '1', signing: view === 'source' ? this.signingState(req) : null }; return this.sendHtml(res, documentPageTitle(row), render.renderDocument(req.project, row, view, ctx), start, req); @@ -2821,6 +3068,26 @@ class IpsModule { return this.sendJson(res, 200, modified ? row.analysed : row.bundle); } + /** The patient's comment on a document (the Patient Comments tab): replaced, or removed when empty. */ + savePatientComment(req, res) { + const id = docId(req.params.id); + if (!this.store.read(id, req.project.id)) { + return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(`No document with id '${req.params.id}'`), 404); + } + const text = typeof req.body?.comment === 'string' ? req.body.comment.replace(/\r\n/g, '\n') : ''; + if (text.length > render.PATIENT_COMMENT_MAX) { + return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(`The comment is too long: it can hold at most ${render.PATIENT_COMMENT_MAX} characters`), 400); + } + // pure markdown only: no HTML at all + const html = patientComments.markdownHtmlParts(text); + if (html.length > 0) { + return htmlServer.sendErrorResponse(res, TEMPLATE, new Error(`The comment has HTML in it (${html[0].length > 60 ? html[0].slice(0, 60) + '...' : html[0]}): only pure markdown is allowed`), 400); + } + this.store.savePatientComment(id, text, req.user.name || req.user.login); + this.log.info(`IPS module: patient comment on document ${id} in '${req.project.code}' ${text.trim() ? 'saved' : 'removed'} by ${req.user.login}`); + res.redirect(`${req.baseUrl}/${encodeURIComponent(req.project.code)}/Bundle/${id}?view=comments&saved=1`); + } + // ---- patients ---- /** @@ -3074,7 +3341,8 @@ class IpsModule { versioning: 'no-version', readHistory: false, updateCreate: false, - searchParam: capabilitySearchParams() + searchParam: capabilitySearchParams(), + operation: [{ name: 'document', definition: DOCUMENT_OPERATION_DEFINITION }] }, { type: 'Patient', documentation: 'The patients of the documents received: each document\'s Patient is matched to one seen before ' + diff --git a/ips/patient-comments.js b/ips/patient-comments.js new file mode 100644 index 00000000..785e0225 --- /dev/null +++ b/ips/patient-comments.js @@ -0,0 +1,171 @@ +// +// Copyright 2026, Health Intersections Pty Ltd (http://www.healthintersections.com.au) +// +// Licensed under BSD-3: https://opensource.org/license/bsd-3-clause +// + +/** + * The patient's comments on a document (the Patient Comments tab): pure markdown, and the + * patient notes section (LOINC 51855-5) they go into when a copy of the document is downloaded + * or shared with "Include Patient Comments". + * + * The order matters (ips.js preparedCopy): any patient notes section already in the document is + * removed before signing; the comments' section is added after signing, so it is not signed. + */ + +const commonmark = require('commonmark'); + +const LOINC = 'http://loinc.org'; +const PATIENT_NOTES = '51855-5'; +const PATIENT_NOTES_TITLE = 'Patient\'s Comments'; +// the most a patient comment can hold (characters) +const PATIENT_COMMENT_MAX = 30000; + +/** CommonMark as HTML, with raw HTML left out and unsafe links dropped. */ +function markdownHtml(md) { + return new commonmark.HtmlRenderer({ safe: true }).render(new commonmark.Parser().parse(md || '')); +} + +/** + * The HTML in some markdown: pure markdown only, no HTML at all (autolinks like are markdown). + * @returns {string[]} each piece of HTML found (empty: none) + */ +function markdownHtmlParts(md) { + const walker = new commonmark.Parser().parse(md || '').walker(); + const found = []; + let e; + while ((e = walker.next())) { + if (e.entering && (e.node.type === 'html_block' || e.node.type === 'html_inline')) { + found.push(e.node.literal.trim()); + } + } + return found; +} + +const isObject = (x) => x !== null && typeof x === 'object' && !Array.isArray(x); + +/** The document's Composition (its first entry), or null. */ +function compositionOf(bundle) { + const r = Array.isArray(bundle?.entry) ? bundle.entry[0]?.resource : null; + return isObject(r) && r.resourceType === 'Composition' ? r : null; +} + +function isPatientNotes(section) { + return isObject(section) && Array.isArray(section.code?.coding) && + section.code.coding.some(c => isObject(c) && c.system === LOINC && c.code === PATIENT_NOTES); +} + +/** Drop patient notes sections (at any depth) from a list of sections. @returns {Array} */ +function withoutNotes(sections) { + return sections.filter(s => !isPatientNotes(s)).map(s => (isObject(s) && Array.isArray(s.section) ? { ...s, section: withoutNotes(s.section) } : s)); +} + +/** + * The document without any patient notes section (LOINC 51855-5) in its Composition. + * @param {Object} bundle - not changed + * @returns {Object} a copy + */ +function removePatientNotes(bundle) { + const doc = structuredClone(bundle); + const comp = compositionOf(doc); + if (comp && Array.isArray(comp.section)) { + comp.section = withoutNotes(comp.section); + if (comp.section.length === 0) { + delete comp.section; + } + } + return doc; +} + +/** The reference to the document's patient: the Composition's subject, else the Patient entry's fullUrl. */ +function patientReference(bundle, comp) { + if (typeof comp.subject?.reference === 'string') { + return comp.subject.reference; + } + const e = bundle.entry.find(x => x?.resource?.resourceType === 'Patient' && typeof x.fullUrl === 'string'); + return e ? e.fullUrl : null; +} + +/** + * The document with the patient's comments as its first section: the patient notes code, the + * title, the patient as author, and the comments as narrative (status additional) - nothing else. + * @param {Object} bundle - not changed + * @param {string} markdown - the comment (pure markdown) + * @returns {Object} a copy + */ +function addPatientComments(bundle, markdown) { + const doc = structuredClone(bundle); + const comp = compositionOf(doc); + if (!comp) { + throw new Error('The document has no Composition to add the patient\'s comments to'); + } + const section = { + title: PATIENT_NOTES_TITLE, + code: { coding: [{ system: LOINC, code: PATIENT_NOTES }] } + }; + const patient = patientReference(doc, comp); + if (patient) { + section.author = [{ reference: patient }]; + } + section.text = { status: 'additional', div: `
${markdownHtml(markdown).trim()}
` }; + comp.section = [section, ...(Array.isArray(comp.section) ? comp.section : [])]; + return doc; +} + +// ---- reading them back from a document -------------------------------------------------------- + +let turndown = null; + +/** The HTML to markdown converter (turndown), set up for pure markdown: made when first needed */ +function converter() { + if (!turndown) { + const TurndownService = require('turndown'); + const t = new TurndownService({ headingStyle: 'atx', bulletListMarker: '-', codeBlockStyle: 'fenced', emDelimiter: '*' }); + // text that looks like HTML is text: '<' is escaped, so the markdown has no HTML in it + t.escape = (text) => TurndownService.prototype.escape.call(t, text).replace(/ '' }); + t.addRule('cell', { filter: ['td', 'th'], replacement: (content, node) => (node.previousElementSibling ? ' | ' : '') + content.replace(/\s+/g, ' ').trim() }); + t.addRule('row', { filter: 'tr', replacement: (content) => `\n\n${content}\n\n` }); + turndown = t; + } + return turndown; +} + +/** A narrative (XHTML) as pure markdown: the best turndown can do, with anything HTML left escaped. */ +function htmlToMarkdown(div) { + let md = converter().turndown(typeof div === 'string' ? div : '').replace(/\n{3,}/g, '\n\n').trim(); + // belt and braces: whatever still reads as HTML is escaped + if (markdownHtmlParts(md).length > 0) { + md = md.replace(/ { + for (const s of Array.isArray(sections) ? sections : []) { + if (isPatientNotes(s)) { + out.push(s); + } else if (isObject(s)) { + walk(s.section); + } + } + }; + walk(compositionOf(bundle)?.section); + return out; +} + +/** + * What a document's patient notes sections say, as markdown (their narratives, one after the + * other), or null when it has none or they say nothing. + */ +function patientNotesMarkdown(bundle) { + const parts = patientNotesSections(bundle).map(s => htmlToMarkdown(s.text?.div)).filter(Boolean); + return parts.length > 0 ? parts.join('\n\n') : null; +} + +module.exports = { PATIENT_NOTES, PATIENT_NOTES_TITLE, PATIENT_COMMENT_MAX, markdownHtml, markdownHtmlParts, removePatientNotes, addPatientComments, htmlToMarkdown, patientNotesMarkdown }; diff --git a/ips/pipeline.js b/ips/pipeline.js index 81e5e741..09a2bbbe 100644 --- a/ips/pipeline.js +++ b/ips/pipeline.js @@ -36,6 +36,10 @@ const { terminologyOf } = require('./terminology'); const { isHl7System } = require('./ips-valuesets'); const { Presenter } = require('./presenter'); +const { removePatientNotes, patientNotesMarkdown, PATIENT_COMMENT_MAX } = require('./patient-comments'); + +// who wrote a patient comment read from the document's own patient notes section +const PATIENT_NOTES_SOURCE = 'the document\'s patient notes section'; const ai = require('./ai-client'); const { evaluateAsync } = require('./fhirpath-ips'); const { checkNarrative } = require('../library/narrative-check'); @@ -122,10 +126,12 @@ function signatureOutcome(o) { /** * Signatures: the document's signatures are checked (signatures.js), on a copy of the - * document as received, with keys from the server's key store (signature-keys.js; a test, or + * document as received - without any patient notes section (LOINC 51855-5) - with keys from the server's key store (signature-keys.js; a test, or * another key store, sets module.keyProvider). What it says is kept as the step's result, and * shown at the top of the analysis view. It gives no note for the status line, and a check * that fails is an error outcome, not a failed step: the rest of the processing goes on. + * A patient notes section (LOINC 51855-5) in the document becomes the document's patient comment, + * converted to markdown (turndown), when it has none yet. */ const signaturesStep = { name: 'signatures', @@ -133,7 +139,9 @@ const signaturesStep = { const started = Date.now(); let outcomes; try { - const found = await withTimeout(signatures.verify(structuredClone(row.bundle), module.keyProvider || new KeyStoreKeyProvider(), + // without any patient notes section (LOINC 51855-5): a copy downloaded or shared with the + // patient's comments has them added there after signing, so the signatures don't cover it + const found = await withTimeout(signatures.verify(removePatientNotes(row.bundle), module.keyProvider || new KeyStoreKeyProvider(), { receivedAt: row.received || null, log: module.log }), module.verifyTimeoutMs || VERIFY_TIMEOUT_MS, `it took more than ${(module.verifyTimeoutMs || VERIFY_TIMEOUT_MS) / 1000} seconds`); outcomes = Array.isArray(found) ? found.map(signatureOutcome) : [{ status: 'error', keyId: null, description: 'The signature check did not return a list of outcomes' }]; @@ -142,6 +150,16 @@ const signaturesStep = { outcomes = [{ status: 'error', keyId: null, description: `The signature check failed: ${e.message}` }]; } module.store.saveResult(row.id, 'signatures', { ms: Date.now() - started, outcomes }); + // a patient notes section the document came with becomes its patient comment (as markdown), + // unless it has one already - one written here is not overwritten by processing again + try { + const md = patientNotesMarkdown(row.bundle); + if (md && !module.store.patientComment(row.id)) { + module.store.savePatientComment(row.id, md.length > PATIENT_COMMENT_MAX ? md.substring(0, PATIENT_COMMENT_MAX) : md, PATIENT_NOTES_SOURCE); + } + } catch (e) { + module.log.error(`IPS module: document ${row.id}: the patient notes section could not be read as the patient's comments: ${e.message}`); + } return null; } }; @@ -834,6 +852,58 @@ async function lookupDisplay(tx, coding) { return (await lookupDisplayAnswer(tx, coding)).display; } +/** + * Generate a document's narrative with the IPS presenter - displays from the module's + * terminology server, if it has one (cached, bounded) - and write it into the document, as the + * Composition's and each section's text (status generated). Used by the narrative step, and for + * a copy downloaded or shared with "Regenerate narrative" (ips.js preparedCopy). + * @param {Object} doc - the document: changed + * @returns {Promise<{out: Object, lookups: number}>} the presenter's output, and how many lookups it made + */ +async function generateNarrative(doc, module) { + const cache = module.txCache || (module.txCache = new Map()); + const budget = { left: MAX_LOOKUPS_PER_DOCUMENT }; + const counts = { lookups: 0 }; + const lookup = module.tx ? async (coding) => { + const key = `lookup|${coding.system}|${coding.version || ''}|${coding.code}`; + if (cache.has(key)) { + return cache.get(key); + } + if (budget.left <= 0) { + return null; + } + budget.left--; + counts.lookups++; + const { display, definite } = await lookupDisplayAnswer(module.tx, coding); + // a server that was down or slow isn't an answer: asked again next time + if (definite) { + if (cache.size >= MAX_CACHED_ANSWERS) { + cache.delete(cache.keys().next().value); + } + cache.set(key, display); + } + return display; + } : null; + const presenter = new Presenter({ lookup }); + const out = await presenter.render(doc); + // the presenter escapes what it takes from the document; checked anyway, as every + // narrative a document brings is, before it is written anywhere or shown + for (const html of [out.html, out.header, ...out.sections.map(s => s.html)]) { + const problem = checkNarrative(html); + if (problem) { + throw new Error(`the generated narrative failed the active content check (${problem})`); + } + } + const composition = doc.entry?.[0]?.resource; + if (composition && composition.resourceType === 'Composition') { + composition.text = { status: 'generated', div: out.header }; + for (const s of out.sections) { + s.section.text = { status: 'generated', div: s.html }; + } + } + return { out, lookups: counts.lookups }; +} + /** * Narrative: generate the document's narrative with the IPS presenter, after translation * (so the translated codings are in it) and before validation (so the validator sees it). @@ -847,54 +917,14 @@ const narrative = { throw new Error('No analysed copy of the document to write to'); } const started = Date.now(); - const cache = module.txCache || (module.txCache = new Map()); - const budget = { left: MAX_LOOKUPS_PER_DOCUMENT }; - const counts = { lookups: 0 }; - // displays from the terminology server, if there is one: cached, bounded - const lookup = module.tx ? async (coding) => { - const key = `lookup|${coding.system}|${coding.version || ''}|${coding.code}`; - if (cache.has(key)) { - return cache.get(key); - } - if (budget.left <= 0) { - return null; - } - budget.left--; - counts.lookups++; - const { display, definite } = await lookupDisplayAnswer(module.tx, coding); - // a server that was down or slow isn't an answer: asked again next time - if (definite) { - if (cache.size >= MAX_CACHED_ANSWERS) { - cache.delete(cache.keys().next().value); - } - cache.set(key, display); - } - return display; - } : null; - const presenter = new Presenter({ lookup }); - const out = await presenter.render(row.analysed); - // the presenter escapes what it takes from the document; checked anyway, as every - // narrative a document brings is, before it is written anywhere or shown - for (const html of [out.html, out.header, ...out.sections.map(s => s.html)]) { - const problem = checkNarrative(html); - if (problem) { - throw new Error(`the generated narrative failed the active content check (${problem})`); - } - } - const composition = row.analysed.entry?.[0]?.resource; - if (composition && composition.resourceType === 'Composition') { - composition.text = { status: 'generated', div: out.header }; - for (const s of out.sections) { - s.section.text = { status: 'generated', div: s.html }; - } - } + const { out, lookups } = await generateNarrative(row.analysed, module); module.store.saveResult(row.id, 'narrative', { ms: Date.now() - started, - lookups: counts.lookups, + lookups, html: out.html, sections: out.sections.map(s => ({ title: s.title, level: s.level, html: s.html })) }); - return `narrative: ${out.sections.length} section${out.sections.length === 1 ? '' : 's'}` + (counts.lookups ? ` (${counts.lookups} display lookup${counts.lookups === 1 ? '' : 's'})` : ''); + return `narrative: ${out.sections.length} section${out.sections.length === 1 ? '' : 's'}` + (lookups ? ` (${lookups} display lookup${lookups === 1 ? '' : 's'})` : ''); } }; @@ -1250,7 +1280,7 @@ const reportsStep = { const STEPS = [signaturesStep, nationalityStep, analysisStep, translate, narrative, validation, national, terminology, profilesStep, aiStep, reportsStep]; module.exports = { - STEPS, signatures: signaturesStep, signatureOutcome, withTimeout, VERIFY_TIMEOUT_MS, analysis: analysisStep, reports: reportsStep, translate, narrative, validation, national, terminology, profiles: profilesStep, ai: aiStep, checkConstraint, valueSetsIn, lookupDisplay, checkConcept, documentForAi, stripAttachments, ATTACHMENT_PLACEHOLDER, assessmentOf, aiSystemPrompt, AI_SYSTEM_PROMPT, checkOf, addCheck, stripChecks, translateConcept, translationOf, defaultSnomedEdition, withSnomedEdition, hasCoding, + STEPS, generateNarrative, signatures: signaturesStep, signatureOutcome, withTimeout, VERIFY_TIMEOUT_MS, analysis: analysisStep, reports: reportsStep, translate, narrative, validation, national, terminology, profiles: profilesStep, ai: aiStep, checkConstraint, valueSetsIn, lookupDisplay, checkConcept, documentForAi, stripAttachments, ATTACHMENT_PLACEHOLDER, assessmentOf, aiSystemPrompt, AI_SYSTEM_PROMPT, checkOf, addCheck, stripChecks, translateConcept, translationOf, defaultSnomedEdition, withSnomedEdition, hasCoding, validateCodeInValueSet, validateCodeInSystem, issueCounts, issueSummary, IPS_BUNDLE_PROFILE, CHECK_EXTENSION, TRANSLATION_EXTENSION, MAX_CHECKS_PER_DOCUMENT, MAX_CACHED_ANSWERS }; diff --git a/ips/readme.md b/ips/readme.md index 37e26dbd..f5fcfe32 100644 --- a/ips/readme.md +++ b/ips/readme.md @@ -94,6 +94,30 @@ limit). The submitter's IP address is recorded, for tracing abuse, and never ret GET /ips/{code}/Bundle?{params} search GET /ips/{code}/metadata CapabilityStatement +`$document` gives the API what the source view's banner gives a browser +([OperationDefinition](OperationDefinition-ips-document.json), referred to from the +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 +`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. + A browser (or `_format=html`) gets pages: `/ips/{code}` is the project's page - its name and description in a banner, "Submit a document" (and, for managers, "Settings") buttons, the filterable list (patient name, gender, document date, document id or patient identifier, @@ -242,6 +266,15 @@ seconds; `sign()` has 30. `sign()` is not written yet: it gives the document bac status line, and a check that fails is an error outcome, not a failed step. `verify()` itself is not written yet: it says so, as an information outcome. +Patient notes: `verify()` gets the document without any patient notes section (LOINC 51855-5), +since a copy downloaded or shared with the patient's comments has them added there after +signing. And a patient notes section the document arrives with becomes its patient comment (the +Patient Comments tab), its narrative converted to markdown with +[turndown](https://github.com/mixmark-io/turndown) (`ips/patient-comments.js`): pure markdown - +text that looks like HTML is escaped, a table row becomes its cells with ` | ` between, images are +dropped - and at most 30000 characters. Only when the document has no comment yet: one written +on the tab isn't overwritten by processing again. + ### Jurisdiction The second step (`ips/nationality.js` - the code still calls it nationality) works out which jurisdiction the document is @@ -412,7 +445,7 @@ fatal issues). A profile whose package can't be loaded, or that the validator ca reason and counts as not checked; it doesn't stop the pipeline. With no national profiles there is nothing to do, and no validator is needed; with some, the step fails, as validation does, without a configured, running validator. -The document's **National Profiles** view lists the profiles as they were when the document was processed, with the +The document's **Jurisdictional Profiles** view lists the profiles as they were when the document was processed, with the outcome (passed, failed, or not checked) and the issue counts for each; a profile's page shows its validation as the validation view shows the base validation (`?view=national&np={n}`). The packages loaded for national profiles stay loaded in the validator alongside its own (`packages`), so two national IGs that define the same things differently can diff --git a/ips/render.js b/ips/render.js index c6dd2b69..0e38b8da 100644 --- a/ips/render.js +++ b/ips/render.js @@ -30,6 +30,7 @@ const { jurisdiction } = require('./jurisdictions'); const { summaryOf, STEP_TIMINGS_SAMPLE } = require('./store'); const { SNOMED_LINKABLE_EDITIONS, editionName } = require('../tx/sct/editions'); const { nationalityText } = require('./nationality'); +const { markdownHtml, PATIENT_COMMENT_MAX } = require('./patient-comments'); // the nations there is a flag for (static/assets/images/flags/{code}.svg); any other is the globe const FLAGS = new Set(['US', 'AU']); @@ -110,7 +111,8 @@ const STYLE = ` .ips-doc-banner-message:empty { display: none; } .ips-doc-actions .btn { font-size: 90%; padding: 2px 10px; } .ips-nav.nav-tabs { margin-bottom: 14px; } - .ips-nav.nav-tabs > li > a { padding: 6px 14px; } + .ips-nav.nav-tabs > li > a { padding: 6px 9px; } + .ips-patient-comment { border: 1px solid #dee2e6; border-radius: 4px; padding: 8px 12px; margin-bottom: 6px; background-color: #fcfcf4; } .ips-explain { margin-top: 18px; padding-top: 8px; border-top: 1px solid #dee2e6; } .ips-filter { display: flex; flex-wrap: wrap; gap: 4px 6px; align-items: center; font-size: 85%; } .ips-filter input, .ips-filter select { font-size: 100%; padding: 1px 4px; height: auto; } @@ -371,13 +373,19 @@ function crumbs(ctx, project, extra) { */ function renderHome(projects, ctx) { let h = STYLE + userBar(ctx); - h += '

Each project is a collection of International Patient Summary documents, with its own FHIR endpoint ' + - '(POST / GET {project}/Bundle) and web pages. ' + - `Clinical profiles say what kinds of clinical document are expected to contain, and ` + - `national profiles are the IPS document profiles that national implementation guides define. ` + - `Reports are tables of data drawn from the documents, with SQL statements summarising them, shown in each project. ` + - `The SHL viewer opens SMART Health Links and Verifiable Health Links that carry IPS documents. ` + - `To make an IPS document - to download, share as a QR code, or submit to a project - compose a document.

`; + h += '

Each project is a collection of International Patient Summary documents. Users can:

' + + '
    ' + + '
  • Upload their own documents through the web or the FHIR API, create a document directly, or through QR Codes (see below)
  • ' + + `
  • Once uploaded, each document is check for validity against international IPS and other jurisdictional IPS variants
  • ` + + '
  • Terminology is converted to international suitable versions where possible, and the document is assessed for international suitability
  • ' + + `
  • The document is checked against clinical criteria for different conditions (Clinical profiles)
  • ` + + '
  • An AI Agent checks the document for coherence
  • ' + + '
  • The original or internationalised document can be downloaded directly, or via the FHIR API or turned into a QR code
  • ' + + '
  • Documents can be signed, and signatures are checked, and patients can comment on the document
  • ' + + '
' + + `

Each project produce Reports (tables of data drawn from the documents). ` + + `In addition, the SHL viewer opens SMART Health Links and Verifiable Health Links that carry IPS documents. ` + + `To make an IPS document - to download, share as a QR code, or submit to a project - compose a document.

`; if (projects.length === 0) { h += '

There are no projects yet' + (ctx.user?.isAdmin ? `: create one` : '') + '.

'; } else { @@ -520,6 +528,10 @@ function projectDocs(project, ctx) { '' + `` + `` + + `' + `' + @@ -1510,6 +1522,73 @@ function renderAi(row, options = {}) { return h; } + +/** + * The Patient Comments view: the one comment the patient makes on the document - the accuracy or + * appropriateness of its content (typically a diagnosis in the problems section). Everyone sees it; + * anyone logged in can write it. + * @param {Object} row - from store.read(), with .comment (store.patientComment) or not + * @param {{base: string, user?: Object, csrf?: string, docUrl: string, here?: string, saved?: boolean}} ctx + */ +function renderPatientComments(row, ctx) { + const c = row.comment; + let h = '

This is a section for any comments the patient wishes to make about the accuracy or appropriateness of the content in the document.

'; + if (ctx.saved) { + h += '
The comment has been saved.
'; + } + if (c) { + h += `
${markdownHtml(c.markdown)}
`; + h += `

Last changed ${escape(c.updated)}${c.by ? ` by ${escape(c.by)}` : ''}

`; + } else { + h += '

The patient has made no comments on this document.

'; + } + if (!ctx.user) { + h += `

Log in to write the patient's comment.

`; + } else { + h += `

${c ? 'Edit the comment' : 'Write a comment'}

`; + h += `${csrfField(ctx.csrf)}`; + h += ''; + h += '' + + `` + + ''; + h += '
'; + h += ``; + h += ``; + } + h += '

The patient\'s own comments on the document - where they take issue with its content, such as a diagnosis in the problems section ' + + '(these are notoriously unreliable). The patient may be right or wrong: the comment is what they say, not a correction. ' + + 'There is one comment per document, written in markdown; it is kept apart from the document, which is not changed, and processing the document again leaves it alone. ' + + 'Everyone can see it; anyone logged in can change it.

'; + return h; +} + /** * The validation view: what the validator made of the document. * @param {Object} row - from store.read(), with .results.validation (from store.readResult) or not @@ -2449,7 +2528,10 @@ function renderSource(row, durl, ctx) { if (!doc) { return h + '

There is no modified copy of this document: it has not been processed yet.

'; } - h += documentBanner(durl, modified, ctx); + h += documentBanner(durl, modified, { ...ctx, hasComment: !!row.comment }); + h += '

The same downloads and shares can be had from the API, with the ' + + '$document operation: ' + + `${escape(durl)}/$document.

`; h += `
${sourceJsonHtml(doc)}
`; h += '

Original is the document as it was submitted. Modified is what the processing ended up with: ' + 'codings added to CodeableConcepts by translation (marked with an extension saying where they came from), the narrative generated by this server, ' + @@ -2490,7 +2572,10 @@ function signChoices(ctx) { * sharing forms, so they work without scripts; the ZIP and the PDF are made in the browser * (doc-actions.js), so their buttons show only when scripts run, as signing does. With a Sign * choice ticked, each download and share is of a signed copy, made by the server when asked - * ({durl}/signed, and the share forms' signUser and signSystem); it isn't kept + * ({durl}/signed, and the share forms' signUser and signSystem); it isn't kept. When the document + * has patient comments, "Include Patient Comments" adds them to each download and share the same + * way (comments), after any signing; "Regenerate narrative" (narrative) has the server generate the + * narrative first, as the narrative step does */ function documentBanner(durl, modified, ctx) { const which = modified ? 'modified' : 'original'; @@ -2504,6 +2589,16 @@ function documentBanner(durl, modified, ctx) { let h = `

`; h += signChoices(ctx); + // the narrative regenerated, as the narrative view's Generated shows it (before any signing) + h += ''; + // the patient's comments, when there are some: added to each copy after it is signed (not signed) + if (ctx.hasComment) { + h += ''; + } h += '
Download' + `JSON` + `` + @@ -2513,7 +2608,7 @@ function documentBanner(durl, modified, ctx) { // page asks for JSON and shows the code in a panel over the page const form = (kind, title, label) => `
` + csrfField(ctx.csrf) + `` + - '' + + '' + ``; h += '
Share' + form('shl', `A SMART Health Link to ${what}, as a QR code`, 'SHL') + @@ -2532,9 +2627,13 @@ function documentBanner(durl, modified, ctx) { var sign = banner.querySelector('.ips-sign'); var signUser = banner.querySelector('[name=sign-user]'); var signSystem = banner.querySelector('[name=sign-system]'); + var comments = banner.querySelector('[name=include-comments]'); + var narrative = banner.querySelector('[name=regenerate-narrative]'); if (sign) { sign.hidden = false; } + if (narrative) { banner.querySelector('.ips-narrative-choice').hidden = false; } + if (comments) { banner.querySelector('.ips-comments-choice').hidden = false; } function signing() { - return { user: !!(signUser && signUser.checked), system: !!(signSystem && signSystem.checked) }; + return { user: !!(signUser && signUser.checked), system: !!(signSystem && signSystem.checked), comments: !!(comments && comments.checked), narrative: !!(narrative && narrative.checked) }; } // the share forms send the choices too function syncShares() { @@ -2542,17 +2641,19 @@ function documentBanner(durl, modified, ctx) { banner.querySelectorAll('.ips-share-form').forEach(function (f) { f.querySelector('[name=signUser]').value = s.user ? '1' : ''; f.querySelector('[name=signSystem]').value = s.system ? '1' : ''; + f.querySelector('[name=comments]').value = s.comments ? '1' : ''; + f.querySelector('[name=narrative]').value = s.narrative ? '1' : ''; }); } - [signUser, signSystem].forEach(function (c) { if (c) { c.addEventListener('change', syncShares); } }); + [signUser, signSystem, comments, narrative].forEach(function (c) { if (c) { c.addEventListener('change', syncShares); } }); syncShares(); - // the document as JSON text: as stored, or a signed copy the server makes now + // the document as JSON text: as stored, or a copy the server makes now (signed, with the patient's comments) function documentJson() { var s = signing(); - var req = s.user || s.system + var req = s.user || s.system || s.comments || s.narrative ? fetch(banner.getAttribute('data-signed'), { method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json', Accept: 'application/fhir+json', 'X-CSRF-Token': banner.getAttribute('data-csrf') }, - body: JSON.stringify({ source: banner.getAttribute('data-source'), user: s.user, system: s.system }) }) + body: JSON.stringify({ source: banner.getAttribute('data-source'), user: s.user, system: s.system, comments: s.comments, narrative: s.narrative }) }) : fetch(banner.getAttribute('data-json'), { headers: { Accept: 'application/fhir+json' }, credentials: 'same-origin' }); return req.then(function (r) { return r.text().then(function (t) { @@ -2568,7 +2669,8 @@ function documentBanner(durl, modified, ctx) { function run(kind, button) { var label = kind.toUpperCase(); if (button) { button.disabled = true; } - message.textContent = (signing().user || signing().system ? 'Signing, and making the ' : 'Making the ') + label + '...'; + var s = signing(); + message.textContent = (s.narrative ? 'Generating the narrative, and making the ' : s.user || s.system ? 'Signing, and making the ' : 'Making the ') + label + '...'; documentJson() .then(function (json) { return window.IpsDocActions.download(kind, { json: json, bundle: JSON.parse(json), name: fileName(), vendor: vendor }); @@ -2582,7 +2684,7 @@ function documentBanner(durl, modified, ctx) { if (jsonLink) { jsonLink.addEventListener('click', function (e) { var s = signing(); - if (s.user || s.system) { + if (s.user || s.system || s.comments || s.narrative) { e.preventDefault(); run('json', null); } @@ -2705,9 +2807,10 @@ const VIEWS = [ ['translation', 'Translation'], ['terminology', 'Terminology'], ['validation', 'Validation'], - ['national', 'National Profiles'], + ['national', 'Jurisdictions'], ['profiles', 'Clinical Profiles'], - ['ai', 'AI Assessment'], + ['ai', 'AI Check'], + ['comments', 'Patient Comments'], ['source', 'Source'] ]; @@ -2772,10 +2875,10 @@ const STEP_LABELS = { translate: ['Translate', 'view=translation'], narrative: ['Narrative', 'view=narrative&narrative=generated'], validation: ['Validation', 'view=validation'], - national: ['National Profiles', 'view=national'], + national: ['Jurisdictions', 'view=national'], terminology: ['Terminology', 'view=terminology'], profiles: ['Clinical Profiles', 'view=profiles'], - ai: ['AI Assessment', 'view=ai'], + ai: ['AI Check', 'view=ai'], reports: ['Reports', null] }; @@ -2849,6 +2952,8 @@ function renderDocument(project, row, view, ctx) { h += renderProfileChecks(row, { base: ctx.base, canManage: ctx.canManage }); } else if (view === 'ai') { h += renderAi(row, { canManage: ctx.canManage }); + } else if (view === 'comments') { + h += renderPatientComments(row, { ...ctx, docUrl: durl }); } else if (view === 'validation') { h += renderValidation(row, { level: ctx.level, docUrl: durl, canManage: ctx.canManage }); } else if (view === 'national') { @@ -3158,6 +3263,6 @@ function renderProjectReport(project, report, out, problem, errors, ctx, maxRows module.exports = { analysisOk, renderHome, renderProjects, renderProject, renderSubmit, renderSettings, renderDocument, - assembledNarrative, renderStructure, renderAnalysis, renderTerminology, renderTranslation, renderGenerated, renderAi, renderValidation, renderNational, renderShare, renderCompose, renderComposeChoice, renderPatientEditor, renderPatients, renderPatient, renderProfileChecks, + 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 }; diff --git a/ips/share.js b/ips/share.js index 3041ecc4..385bee21 100644 --- a/ips/share.js +++ b/ips/share.js @@ -26,6 +26,7 @@ const crypto = require('crypto'); const jose = require('jose'); const qrcode = require('qrcode-generator'); +const zlib = require('zlib'); const { dispatch } = require('./tx-client'); const DEFAULT_VIEWER = 'https://viewer.tcpdev.org/#'; @@ -181,6 +182,50 @@ function qrSvg(text) { return qr.createSvgTag({ cellSize: 4, margin: 8, scalable: true }); } +/** + * A QR code (error correction L) as a PNG: black on white, 1 bit grey, `scale` pixels a module, + * a 4 module quiet zone. For the API ($document), where the web page has the SVG. + * @returns {Buffer} + */ +function qrPng(text, scale = 8) { + const qr = qrcode(0, 'L'); + qr.addData(text); + qr.make(); + const margin = 4; + const n = qr.getModuleCount(); + const size = (n + 2 * margin) * scale; + const rowBytes = Math.ceil(size / 8); + const raw = Buffer.alloc((rowBytes + 1) * size, 0); + for (let y = 0; y < size; y++) { + const row = y * (rowBytes + 1); + raw[row] = 0; // filter: none + for (let x = 0; x < size; x++) { + const mx = Math.floor(x / scale) - margin; + const my = Math.floor(y / scale) - margin; + const dark = mx >= 0 && my >= 0 && mx < n && my < n && qr.isDark(my, mx); + // 1 bit grey: 1 is white + if (!dark) { + raw[row + 1 + (x >> 3)] |= 0x80 >> (x & 7); + } + } + } + const chunk = (type, data) => { + const len = Buffer.alloc(4); + len.writeUInt32BE(data.length); + const body = Buffer.concat([Buffer.from(type, 'ascii'), data]); + const crc = Buffer.alloc(4); + crc.writeUInt32BE(zlib.crc32(body)); + return Buffer.concat([len, body, crc]); + }; + const ihdr = Buffer.alloc(13); + ihdr.writeUInt32BE(size, 0); + ihdr.writeUInt32BE(size, 4); + ihdr[8] = 1; // bit depth + ihdr[9] = 0; // greyscale + return Buffer.concat([Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]), + chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]); +} + /** * Is this SHL server URL this server's own shl module: http(s), the host of hostName or of * publicUrl, and the path /shl? (Then the ips module calls it in process, as this server.) @@ -211,4 +256,4 @@ function isOwnShlServer(server, { hostName, publicUrl } = {}) { return hosts.has(u.host.toLowerCase()) && u.pathname.replace(/\/+$/, '') === '/shl'; } -module.exports = { ShlClient, qrSvg, isOwnShlServer, DEFAULT_VIEWER, DEFAULT_DAYS, MAX_SHARE_BYTES }; +module.exports = { ShlClient, qrSvg, qrPng, isOwnShlServer, DEFAULT_VIEWER, DEFAULT_DAYS, MAX_SHARE_BYTES }; diff --git a/ips/signatures.js b/ips/signatures.js index f57c4475..96a1f212 100644 --- a/ips/signatures.js +++ b/ips/signatures.js @@ -90,6 +90,13 @@ * Returns (a promise of) the signed document, as parsed JSON. Throw to refuse: the message is * shown to the user. The signed document is not kept: it is downloaded, or shared, as it is. * + * Patient comments (ips/patient-comments.js): when the user asks for them to be included, any + * patient notes section (LOINC 51855-5) is removed from `bundle` before sign() sees it, and the + * patient's comments are added afterwards, as the Composition's first section (LOINC 51855-5): + * they are not signed, so the signed document a recipient gets has a section the signature did + * not cover. So verify() is given the document with any patient notes section removed (the + * signatures step does it): the signature covers the document without that section. + * * A signer is * * { diff --git a/ips/store.js b/ips/store.js index a8d4cc7c..9e55bed1 100644 --- a/ips/store.js +++ b/ips/store.js @@ -106,6 +106,16 @@ const SCHEMA = ` PRIMARY KEY (doc_id, step) ); + -- the patient's comments on a document (the Patient Comments tab): one per document, CommonMark, + -- kept apart from the document (which is never altered) and from the step results (so processing + -- again leaves it alone) + CREATE TABLE IF NOT EXISTS patient_comments ( + doc_id INTEGER PRIMARY KEY REFERENCES documents(id) ON DELETE CASCADE, + markdown TEXT NOT NULL, + updated_ms INTEGER NOT NULL, + updated_by TEXT + ); + -- the AI assessment calls made, per project: for the daily cap, and what they cost CREATE TABLE IF NOT EXISTS ai_calls ( id INTEGER PRIMARY KEY AUTOINCREMENT, @@ -987,6 +997,24 @@ class IpsStore { return 'queued'; } + // ---- the patient's comments ---- + + /** @returns {{markdown: string, updated: string, by: string|null}|null} the document's patient comment */ + patientComment(docId) { + const row = this.db.prepare('SELECT markdown, updated_ms, updated_by FROM patient_comments WHERE doc_id = ?').get(docId); + return row ? { markdown: row.markdown, updated: new Date(row.updated_ms).toISOString(), by: row.updated_by } : null; + } + + /** Keep the document's patient comment, replacing the one before; empty (or only spaces) removes it. */ + savePatientComment(docId, markdown, by, nowMs = Date.now()) { + if (!markdown || !markdown.trim()) { + this.db.prepare('DELETE FROM patient_comments WHERE doc_id = ?').run(docId); + return; + } + this.db.prepare('INSERT OR REPLACE INTO patient_comments (doc_id, markdown, updated_ms, updated_by) VALUES (?, ?, ?, ?)') + .run(docId, markdown, nowMs, by || null); + } + // ---- the processing steps' results ---- /** Keep what a step made of a document, replacing any earlier run's. */ From feef8a52ea771cf9dd2913feb4fa0b1cd88d54dd Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Sun, 22 Nov 2026 19:53:23 +1100 Subject: [PATCH 2/3] Improve LOINC lookup --- tx/cs/cs-loinc.js | 3 +- tx/tx-html.js | 184 +++++++++++++++++++++++++++++++++++++++------- 2 files changed, 161 insertions(+), 26 deletions(-) diff --git a/tx/cs/cs-loinc.js b/tx/cs/cs-loinc.js index bc2f1c2f..6163114b 100644 --- a/tx/cs/cs-loinc.js +++ b/tx/cs/cs-loinc.js @@ -599,7 +599,8 @@ class LoincServices extends BaseCSServices { this._addStringProperty(params, 'property', row.Relationship, row.Value || row.Code) .part.push({name: 'partCode', valueCode: row.Code}); } else { - this._addCodeProperty(params, 'property', row.Relationship, row.Code); + // the code's display as the description, so a reader needn't look the code up + this._addCodeProperty(params, 'property', row.Relationship, row.Code, null, row.Value || null); } } } diff --git a/tx/tx-html.js b/tx/tx-html.js index e5528ae4..c1aa56a6 100644 --- a/tx/tx-html.js +++ b/tx/tx-html.js @@ -770,18 +770,72 @@ class TxHtmlRenderer { html += '
'; html += ''; - if (json.parameter && Array.isArray(json.parameter)) { - for (const param of json.parameter) { - html += await this.renderParameter(param, codes); + // Properties and designations ($lookup) are pulled out of the main table into a + // table each below it, where every part becomes a column. + const params = Array.isArray(json.parameter) ? json.parameter : []; + // In a $lookup response, "name" is the name of the code system, not of the concept + const isLookup = params.some((p) => p.name === 'name') && params.some((p) => p.name === 'display'); + const tabled = { property: [], designation: [] }; + for (const param of params) { + if (Object.prototype.hasOwnProperty.call(tabled, param.name) && Array.isArray(param.part)) { + tabled[param.name].push(param); + } else { + html += await this.renderParameter(param, codes, isLookup && param.name === 'name' ? 'Code System name' : null); } } html += '
Request
POST ${purl}/Bundlesubmit 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), ` + + '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) - ' + + '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, ...; ' + 'with _sort, _count, _offset, _summary=count, and processing-status for where a document is in the pipeline (the CapabilityStatement lists them all)
NameValue
'; + html += await this.renderPartsTable('Properties', tabled.property, codes); + html += await this.renderPartsTable('Designations', tabled.designation, codes); html += this.renderJsonSource(json); return html; } + /** + * A table of repeating parameters that each have parts (the properties or the + * designations of a $lookup response): one row per parameter, one column per part + * name, in the order the part names first appear. A part that repeats in a row (an + * additionalUse, a subproperty) is listed in the one cell. Nothing is rendered when + * there are no rows. + */ + async renderPartsTable(title, rows, codes) { + if (!rows.length) { + return ''; + } + const columns = []; + for (const row of rows) { + for (const part of row.part) { + const name = part.name || ''; + if (!columns.includes(name)) { + columns.push(name); + } + } + } + let html = `

${escape(title)}

`; + html += ''; + html += ''; + for (const col of columns) { + html += ``; + } + html += ''; + for (const row of rows) { + html += ''; + for (const col of columns) { + const values = []; + for (const part of row.part) { + if ((part.name || '') === col) { + values.push(await this.renderParameterValue(part, codes, row.name)); + } + } + html += ``; + } + html += ''; + } + html += '
${escape(col)}
${values.join('
')}
'; + return html; + } + /** * The "Show JSON Source" disclosure: the resource as it went on the wire, for * anything the HTML rendering summarises or leaves out. @@ -801,9 +855,9 @@ class TxHtmlRenderer { /** * Render a single parameter row */ - async renderParameter(param, codes) { + async renderParameter(param, codes, label = null) { let html = ''; - html += `${escape(param.name || '')}`; + html += `${escape(label || param.name || '')}`; html += ''; html += await this.renderParameterValue(param, codes, null); html += ''; @@ -819,25 +873,50 @@ class TxHtmlRenderer { * into it. Building a checker here means the code system is built once for the page * rather than once per property. * + * Codings name their own code system, which may be another one (a designation's use, + * say); checkers for those are built when first needed, once per code system for the + * page (checkers). + * * @param {Object} json a Parameters resource - * @returns {Promise<{system: string, version: string|null, exists: function}|null>} + * @returns {Promise<{system: string|null, version: string|null, exists: function|null, checkers: Map}|null>} + * null when this page can't link codes at all; exists is null when the server does + * not have the code system the response is about */ async parametersCodeContext(json) { - const value = (name) => (json.parameter || []).find((p) => p.name === name); - const system = value('system')?.valueUri || value('system')?.valueString; - if (!system || !this.renderer?.linkResolver?.codeChecker || !this.renderer.opContext) { + if (!this.renderer?.linkResolver?.codeChecker || !this.renderer.opContext) { return null; } + const value = (name) => (json.parameter || []).find((p) => p.name === name); + const system = value('system')?.valueUri || value('system')?.valueString || null; const version = value('version')?.valueString || null; - try { - const exists = await this.renderer.linkResolver.codeChecker(this.renderer.opContext, system, version); - return exists ? { system, version, exists } : null; - } catch (e) { - // A link is a courtesy; failing to work out whether to offer one is not a reason - // to fail the page. - debugLog(e); - return null; + const codes = { system, version, exists: null, checkers: new Map() }; + if (system) { + codes.exists = await this.codeCheckerFor(codes, system, version); } + return codes; + } + + /** + * The checker for a code system, built once for the page however many codes from it + * there are. + * + * @returns {Promise} null if the server does not have the code system + */ + codeCheckerFor(codes, system, version) { + const key = system + '|' + (version || ''); + if (!codes.checkers.has(key)) { + codes.checkers.set(key, (async () => { + try { + return (await this.renderer.linkResolver.codeChecker(this.renderer.opContext, system, version)) || null; + } catch (e) { + // A link is a courtesy; failing to work out whether to offer one is not a reason + // to fail the page. + debugLog(e); + return null; + } + })()); + } + return codes.checkers.get(key); } /** @@ -855,7 +934,7 @@ class TxHtmlRenderer { */ async renderPropertyCode(code, codes) { const plain = `${escape(code)}`; - if (!codes) { + if (!codes || !codes.exists) { return plain; } let display; @@ -899,6 +978,9 @@ class TxHtmlRenderer { // Check for complex datatypes if (param.valueCoding) { + if (parentName === 'designation' && ['use', 'additionalUse'].includes(param.name)) { + return await this.renderDesignationUse(param.valueCoding, codes); + } return await this.renderCoding(param.valueCoding, codes); } if (param.valueCodeableConcept) { @@ -999,13 +1081,23 @@ class TxHtmlRenderer { parts.push(escape(coding.system)); } if (coding.code) { - // A Coding says which code system it is in, so it can be linked - but only when - // that is the code system this page already built a checker for. Building one per - // coding would mean building a code system per row. - const sameSystem = codes && coding.system === codes.system - && (!coding.version || !codes.version || coding.version === codes.version); - parts.push(sameSystem - ? await this.renderPropertyCode(coding.code, codes) + // A Coding says which code system it is in, so it can be linked to $lookup on it, + // in whatever code system that is (a designation's use is often from another), + // if the server has it - checked with that code system's checker, built once for + // the page however many codings name it + let target = null; + if (codes && coding.system) { + const sameSystem = coding.system === codes.system + && (!coding.version || !codes.version || coding.version === codes.version); + if (sameSystem) { + target = codes; + } else { + const exists = await this.codeCheckerFor(codes, coding.system, coding.version || null); + target = exists ? { system: coding.system, version: coding.version || null, exists } : null; + } + } + parts.push(target + ? await this.renderPropertyCode(coding.code, target) : `${escape(coding.code)}`); } if (coding.display) { @@ -1018,6 +1110,48 @@ class TxHtmlRenderer { return parts.join(' | ') || '(empty coding)'; } + /** + * A designation's use: what the reader wants is what kind of designation it is + * (Synonym, Fully specified name), so it is shown as its display, linked to $lookup on + * the code where that will work, with the system and code in its title. With no display + * in the coding, the code system's display for it is used; with neither, the code. + */ + async renderDesignationUse(coding, codes) { + if (!coding || !coding.code) { + return coding ? await this.renderCoding(coding, codes) : ''; + } + const id = (coding.system ? coding.system + '#' : '') + coding.code + + (coding.version ? ' (version: ' + coding.version + ')' : ''); + let target = null; + if (codes && coding.system) { + const sameSystem = coding.system === codes.system + && (!coding.version || !codes.version || coding.version === codes.version); + if (sameSystem) { + target = codes.exists ? codes : null; + } else { + const exists = await this.codeCheckerFor(codes, coding.system, coding.version || null); + target = exists ? { system: coding.system, version: coding.version || null, exists } : null; + } + } + let display = coding.display || null; + let link = null; + if (target) { + try { + const known = await target.exists(coding.code); + if (known !== null && known !== undefined) { + display = display || known || null; + link = this.renderer.linkResolver.lookupLink(target.system, target.version, coding.code); + } + } catch (e) { + debugLog(e); + } + } + const text = display ? escape(display) : `${escape(coding.code)}`; + return link + ? `${text}` + : `${text}`; + } + /** * Render CodeableConcept datatype */ From d57712503805c9ae5df5444093005ca5c37c3f70 Mon Sep 17 00:00:00 2001 From: Grahame Grieve Date: Sun, 22 Nov 2026 19:53:40 +1100 Subject: [PATCH 3/3] update tests --- CHANGELOG.md | 6 + package-lock.json | 20 ++ package.json | 1 + tests/cs/cs-loinc.test.js | 20 ++ tests/ips/ips.test.js | 389 ++++++++++++++++++++++++++++- tests/ips/patient-comments.test.js | 74 ++++++ tests/tx/html-lookup-links.test.js | 172 ++++++++++++- 7 files changed, 673 insertions(+), 9 deletions(-) create mode 100644 tests/ips/patient-comments.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index c4fb38c1..091d6bda 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - IPS: the source view's banner can sign what is downloaded or shared: as the logged in user (with a key pair in the key store of a type `ips/signatures.js` can use), as the system, or both. The signed copy is made when asked and not kept; the system signs for anyone, no more than once every `modules.ips.signing.systemSeconds` (10) per address. The signing itself (`sign()` in `ips/signatures.js`) is not written yet, and gives the document back as it was - Keys: an account can't be called System, and a key's owner is shown with its kind (System, or User: name; `ownerKind` in the JWKS); `/keys/api` takes API tokens only; key pairs are made off the event loop; the private key database has no WAL - Keys: `loadPrivateKey` gives a module a private key to sign with itself (logged, with what it is for, and in the daily report) +- 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 - 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 @@ -30,6 +34,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed +- 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 - ETags: a stored resource that is read (a CodeSystem, ValueSet or ConceptMap by id) has an ETag worked out from where it came from - the package (id#version) and the resource's type and id, or the hash VSAC's database keeps - with the server's version, the format and the FHIR version: nothing is hashed, and it's the same in every process, across restarts, and on every server running the same release with the same packages. Resources from a folder or file the server loads still have a hash of their content. Clients that keep ETags get each resource once more. Nothing else gets an ETag from Express any more (it hashed every response body, POSTs included, and no client revalidates an operation or a search); static files keep theirs diff --git a/package-lock.json b/package-lock.json index 91f9490e..a0c1a7df 100644 --- a/package-lock.json +++ b/package-lock.json @@ -42,6 +42,7 @@ "re2js": "^2.8.0", "sqlite3": "^6.0.1", "tar": "^7.5.7", + "turndown": "^7.2.5", "winston": "^3.19.0", "winston-daily-rotate-file": "^4.7.1", "yaml": "^2.8.2" @@ -1872,6 +1873,12 @@ "integrity": "sha512-BqzK8+iHqxUbPRZV6NBum63CJzE0G6vGG3o+4dqeIzbywdoTg+xHJbksYDkk1P1w3Gj64U20Rgp44HHciLbRzg==", "license": "MIT" }, + "node_modules/@mixmark-io/domino": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/@mixmark-io/domino/-/domino-2.2.0.tgz", + "integrity": "sha512-Y28PR25bHXUg88kCV7nivXrP2Nj2RueZ3/l/jdx6J9f8J4nsEGcgX0Qe6lt7Pa+J79+kPiJU3LguR6O/6zrLOw==", + "license": "BSD-2-Clause" + }, "node_modules/@mongodb-js/saslprep": { "version": "1.6.3", "resolved": "https://registry.npmjs.org/@mongodb-js/saslprep/-/saslprep-1.6.3.tgz", @@ -9673,6 +9680,19 @@ "node": "*" } }, + "node_modules/turndown": { + "version": "7.2.5", + "resolved": "https://registry.npmjs.org/turndown/-/turndown-7.2.5.tgz", + "integrity": "sha512-EKZvCCFHh8sWttpAMs10U6niZFJ2cpz8LkCPlylxoG4JcHF50J7EHnnBW3AY1qXtUMu7kDjCp7dnggB1sIbqEQ==", + "license": "MIT", + "dependencies": { + "@mixmark-io/domino": "^2.2.0" + }, + "engines": { + "node": ">=18", + "npm": ">=9" + } + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", diff --git a/package.json b/package.json index 19ff9946..85131c6f 100644 --- a/package.json +++ b/package.json @@ -67,6 +67,7 @@ "re2js": "^2.8.0", "sqlite3": "^6.0.1", "tar": "^7.5.7", + "turndown": "^7.2.5", "winston": "^3.19.0", "winston-daily-rotate-file": "^4.7.1", "yaml": "^2.8.2" diff --git a/tests/cs/cs-loinc.test.js b/tests/cs/cs-loinc.test.js index 3a4d3479..f115582a 100644 --- a/tests/cs/cs-loinc.test.js +++ b/tests/cs/cs-loinc.test.js @@ -1519,6 +1519,26 @@ describe('LOINC Provider', () => { expect(mappingProps(params).map(p => p.value.code)).toEqual(['10828004']); }); + // A code-valued property carries the display of the code it names as its description, + // so a reader of the $lookup response needn't look each code up + test('code-valued properties have the code\'s display as their description', async () => { + const params = []; + await provider.extendLookup('100007-4', ['COMPONENT'], params); + const component = params.find(p => p.name === 'property' && p.part[0].valueCode === 'COMPONENT'); + expect(component.part.find(x => x.name === 'value').valueCode).toBe('LP430726-2'); + expect(component.part.find(x => x.name === 'description').valueString) + .toBe('Demonstrates knowledge of pain management'); + + const parents = []; + await provider.extendLookup('LP14355-9', ['parent'], parents); + const parent = parents.find(p => p.name === 'property' && p.part[0].valueCode === 'parent'); + expect(parent.part.find(x => x.name === 'description').valueString).toBe('Renal function'); + }); + + test('expansion properties do not carry the description', async () => { + expect(await provider.properties('100007-4', ['COMPONENT'])).toEqual([{ code: 'COMPONENT', valueCode: 'LP430726-2' }]); + }); + // LP14355-9 Creatinine is listed under LP31398-8 Renal function on two paths in // ComponentHierarchyBySystem. It has that parent once, and is that part's child once test('a part listed twice under the same parent has it as parent once', async () => { diff --git a/tests/ips/ips.test.js b/tests/ips/ips.test.js index e09db35d..3e2237f8 100644 --- a/tests/ips/ips.test.js +++ b/tests/ips/ips.test.js @@ -474,7 +474,7 @@ describe('the web pages', () => { expect(structure.text).toContain('Medication Summary (empty)'); // the tabs, in order expect([...page.text.matchAll(/([^<]+)<\/a><\/li>/g)].map(m => m[1])) - .toEqual(['Narrative', 'Structure', 'Analysis', 'Translation', 'Terminology', 'Validation', 'National Profiles', 'Clinical Profiles', 'AI Assessment', 'Source']); + .toEqual(['Narrative', 'Structure', 'Analysis', 'Translation', 'Terminology', 'Validation', 'Jurisdictions', 'Clinical Profiles', 'AI Check', 'Patient Comments', 'Source']); expect(page.text).toContain('Provided'); expect((await html('/ips/demo/Bundle/9')).status).toBe(404); const dl = await request(app).get('/ips/demo/Bundle/1?download=1').set('Accept', 'text/html'); @@ -1236,7 +1236,7 @@ describe('the national profiles step', () => { expect(mod.store.read(1)).toMatchObject({ status: 'processed', status_message: 'national profiles: none' }); expect(mod.store.readResult(1, 'national').result).toMatchObject({ profiles: [] }); const page = await request(app).get('/ips/demo/Bundle/1?view=national').set('Accept', 'text/html'); - expect(page.text).toContain('
  • National Profiles
  • '); + expect(page.text).toContain('
  • Jurisdictions
  • '); expect(page.text).toContain('There were no national profiles to validate the document against'); }); @@ -2022,7 +2022,7 @@ describe('the AI assessment step', () => { expect(r.cost).toBeCloseTo(0.0004, 8); expect(r.bytesSent).toBeGreaterThan(1000); const page = await aiView(2); - expect(page).toContain('
  • AI Assessment
  • '); + expect(page).toContain('
  • AI Check
  • '); expect(page).toContain("by server-model-2026 (openai, the server's account), without the narrative"); expect(page).toContain('100 tokens in, 20 out ($0.0004)'); expect(page).toContain('Grade A Consistent ('); @@ -2206,12 +2206,57 @@ describe('sharing as SHL / VHL', () => { }); afterEach(() => mod.shutdown()); + test('shares a document with the patient\'s comments as its first section, when asked', async () => { + await post(app, 'demo', ips()); + mod.store.savePatientComment(1, 'Not *my* allergy', 'Jane'); + const share = (comments) => request(app).post('/ips/demo/Bundle/1/share').set('Origin', 'http://example.org').set('Host', 'example.org') + .set('Accept', 'application/json').type('form').send({ kind: 'shl', comments }); + const shared = async (r) => { + const payload = JSON.parse(Buffer.from(r.body.text.substring(r.body.text.indexOf('shlink:/') + 8), 'base64url').toString('utf8')); + const jwe = Buffer.from(mod.shlEntries.get(payload.url.split('/').pop()).files[0].cnt, 'base64').toString('utf8'); + return JSON.parse(Buffer.from((await jose.compactDecrypt(jwe, Buffer.from(payload.key, 'base64url'))).plaintext).toString('utf8')); + }; + let r = await share('1'); + expect(r.status).toBe(200); + const first = (await shared(r)).entry[0].resource.section[0]; + expect(first.title).toBe('Patient\'s Comments'); + expect(first.text).toEqual({ status: 'additional', div: '

    Not my allergy

    ' }); + // not asked: as stored + r = await share(''); + expect(await shared(r)).toEqual(mod.store.read(1).bundle); + // asked, with none + mod.store.savePatientComment(1, '', 'Jane'); + expect((await share('1')).status).toBe(409); + }); + + test('$document as an SHL or VHL: the QR code as a PNG, the link in headers; the shared copy is the prepared one', async () => { + await post(app, 'demo', ips()); + mod.store.savePatientComment(1, 'Mine', 'Jane'); + const png = (r) => r.buffer(true).parse((res, cb) => { const c = []; res.on('data', d => c.push(d)); res.on('end', () => cb(null, Buffer.concat(c))); }); + let r = await png(request(app).get('/ips/demo/Bundle/1/$document?patient-notes=true').set('Host', 'example.org').set('Accept', 'application/smart-health-link')); + expect(r.status).toBe(200); + expect(r.headers['content-type']).toBe('image/png'); + expect(r.body.subarray(0, 8)).toEqual(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])); + const text = r.headers['x-health-link']; + expect(text.startsWith('https://viewer.example.org/#shlink:/')).toBe(true); + expect(r.headers['x-health-link-manifest']).toBe('https://example.org/shl/access/u1'); + expect(new Date(r.headers['x-health-link-expires']).getTime()).toBeGreaterThan(Date.now()); + const payload = JSON.parse(Buffer.from(text.substring(text.indexOf('shlink:/') + 8), 'base64url').toString('utf8')); + const jwe = Buffer.from(mod.shlEntries.get('u1').files[0].cnt, 'base64').toString('utf8'); + const shared = JSON.parse(Buffer.from((await jose.compactDecrypt(jwe, Buffer.from(payload.key, 'base64url'))).plaintext).toString('utf8')); + expect(shared.entry[0].resource.section[0].title).toBe('Patient\'s Comments'); + r = await png(request(app).get('/ips/demo/Bundle/1/$document?_format=vhl').set('Host', 'example.org')); + expect(r.status).toBe(200); + expect(r.headers['content-type']).toBe('image/png'); + expect(calls.some(c => c.sign)).toBe(true); + }); + test('shares a document as an SHL: encrypted on the SHL server, the key in the link, the QR of the viewer link', async () => { await post(app, 'demo', ips()); // the buttons are on the source view, under the original / modified switch expect((await request(app).get('/ips/demo/Bundle/1').set('Accept', 'text/html')).text).not.toContain('class="ips-inline ips-share-form"'); const page = await request(app).get('/ips/demo/Bundle/1?view=source').set('Accept', 'text/html'); - expect(page.text).toContain(''); + expect(page.text).toContain(''); expect(page.text).toContain('as a QR code">VHL'); expect(page.text).toContain('id="ips-share"'); const r = await request(app).post('/ips/demo/Bundle/1/share').set('Origin', 'http://example.org').set('Host', 'example.org').set('Accept', 'application/json').type('form').send({ kind: 'shl' }); @@ -2289,7 +2334,7 @@ describe('sharing as SHL / VHL', () => { mod.store.saveAnalysed(1, modified); const page = await request(app).get('/ips/demo/Bundle/1?view=source&source=modified').set('Accept', 'text/html'); expect(page.text).toContain(''); + expect(page.text).toContain(''); expect(page.text).toContain('"modified-copy"'); const r = await share(); expect(r.status).toBe(200); @@ -3218,6 +3263,18 @@ describe('the module reads its own request bodies', () => { }); afterEach(() => mod.shutdown()); + test('$document reads its own Parameters (POST)', async () => { + await request(app).post('/ips/open/Bundle').set('Content-Type', 'application/fhir+json').send(JSON.stringify(ips())); + const id = mod.store.list(mod.store.projectByCode('open').id)[0].id; + const r = await request(app).post(`/ips/open/Bundle/${id}/$document`).set('Content-Type', 'application/fhir+json') + .send(JSON.stringify({ resourceType: 'Parameters', parameter: [{ name: 'source', valueCode: 'original' }] })); + expect(r.status).toBe(200); + expect(r.body.resourceType).toBe('Bundle'); + const bad = await request(app).post(`/ips/open/Bundle/${id}/$document`).set('Content-Type', 'application/fhir+json') + .send(JSON.stringify({ resourceType: 'Parameters', parameter: [{ name: 'source', valueCode: 'both' }] })); + expect(bad.status).toBe(400); + }); + test('a document arrives as fhir+json or json, no bigger than maxSize, and the token comes first', async () => { const r1 = await request(app).post('/ips/open/Bundle').set('Content-Type', 'application/fhir+json').send(JSON.stringify(ips())); expect(r1.status).toBe(201); @@ -3797,6 +3854,66 @@ describe("a document's page title", () => { }); }); +describe('patient comments', () => { + test('anyone can see the comment; anyone logged in can write, replace and remove it', async () => { + const { app, mod } = await makeApp(); + try { + mod.store.createProject('demo', 'Demo', null); + await post(app, 'demo', ips()); + const page = (agent) => agent.get('/ips/demo/Bundle/1?view=comments').set('Accept', 'text/html'); + + // not logged in: the tab and its explanation, no comment, no form, and no posting + let res = await page(request(app)); + expect(res.status).toBe(200); + expect(res.text).toContain('Patient Comments'); + expect(res.text).toContain('comments the patient wishes to make about the accuracy or appropriateness'); + expect(res.text).toContain('made no comments'); + expect(res.text).not.toContain('name="comment"'); + expect((await request(app).post('/ips/demo/Bundle/1/comment').type('form').send({ comment: 'x' })).status).toBe(403); + expect(mod.store.patientComment(1)).toBeNull(); + + // any logged in user writes it: pure markdown, no HTML at all (block or inline); autolinks are markdown + await makeUser('jane', 'password1', { name: 'Jane Smith' }); + const jane = (await loginAs(app, 'jane', 'password1')).agent; + expect((await page(jane)).text).toContain('name="comment"'); + for (const bad of ['I had asthma.\n\n', 'I never had asthma', '', '
    \nx\n
    ']) { + res = await form(jane, '/ips/demo/Bundle/1/comment', { comment: bad }); + expect(res.status).toBe(400); + expect(res.text).toContain('only pure markdown is allowed'); + } + expect(mod.store.patientComment(1)).toBeNull(); + res = await form(jane, '/ips/demo/Bundle/1/comment', { comment: 'I **never** had asthma: see and 2 < 3.\r\n' }); + expect(res.status).toBe(302); + expect(res.headers.location).toBe('/ips/demo/Bundle/1?view=comments&saved=1'); + expect(mod.store.patientComment(1)).toMatchObject({ markdown: 'I **never** had asthma: see and 2 < 3.\n', by: 'Jane Smith' }); + res = await page(request(app)); + expect(res.text).toContain('I never had asthma: see
    https://example.org/x and 2 < 3.'); + expect(res.text).toContain('by Jane Smith'); + + // one per document: saving again replaces it; processing again leaves it; empty removes it + await form(jane, '/ips/demo/Bundle/1/comment', { comment: 'Second thoughts' }); + expect(mod.store.patientComment(1).markdown).toBe('Second thoughts'); + mod.store.requeue(1, mod.store.projectByCode('demo').id); + mod.store.clearResults(1); + expect(mod.store.patientComment(1).markdown).toBe('Second thoughts'); + await form(jane, '/ips/demo/Bundle/1/comment', { comment: ' ' }); + expect(mod.store.patientComment(1)).toBeNull(); + + // no such document; too long; no CSRF token + expect((await form(jane, '/ips/demo/Bundle/99/comment', { comment: 'x' })).status).toBe(404); + expect((await form(jane, '/ips/demo/Bundle/1/comment', { comment: 'x'.repeat(30001) })).status).toBe(400); + expect((await jane.post('/ips/demo/Bundle/1/comment').type('form').send({ comment: 'x' })).status).toBe(403); + + // deleting the document deletes its comment + await form(jane, '/ips/demo/Bundle/1/comment', { comment: 'Kept until the document goes' }); + mod.store.delete(1, mod.store.projectByCode('demo').id); + expect(mod.store.db.prepare('SELECT COUNT(*) AS n FROM patient_comments').get().n).toBe(0); + } finally { + mod.shutdown(); + } + }); +}); + describe('patients: matching, the Patient endpoint, $summary', () => { let app; let mod; @@ -3989,6 +4106,34 @@ describe('the signatures step', () => { expect(page.text).toContain('>Warning k2: The key is expired but the signature was valid'); }); + test('verify gets the document without any patient notes section (they are added after signing)', async () => { + const spy = jest.spyOn(signatures, 'verify').mockResolvedValue([]); + const doc = ips(); + doc.entry[0].resource.section.unshift({ title: 'Patient\'s Comments', code: { coding: [{ system: 'http://loinc.org', code: '51855-5' }] }, text: { status: 'additional', div: '
    x
    ' } }); + await post(app, 'demo', doc); + await mod.processQueue(); + expect(spy.mock.calls[0][0].entry[0].resource.section.map(x => x.title)).toEqual(['Allergies and Intolerances', 'Medication Summary']); + // the stored document keeps it + expect(mod.store.read(1).bundle.entry[0].resource.section.length).toBe(3); + }); + + test('a patient notes section becomes the patient comment, as markdown - unless there is one already', async () => { + jest.spyOn(signatures, 'verify').mockResolvedValue([]); + const notes = { title: 'Patient Notes', code: { coding: [{ system: 'http://loinc.org', code: '51855-5' }] }, text: { status: 'additional', div: '

    The asthma is wrong

    ' } }; + const doc = ips(); + doc.entry[0].resource.section.push(notes); + await post(app, 'demo', doc); + await post(app, 'demo', ips()); + await mod.processQueue(); + expect(mod.store.patientComment(1)).toMatchObject({ markdown: 'The **asthma** is wrong', by: 'the document\'s patient notes section' }); + expect(mod.store.patientComment(2)).toBeNull(); + // processing again doesn't overwrite one written since + mod.store.savePatientComment(1, 'Edited', 'Jane'); + mod.store.requeue(1, mod.store.projectByCode('demo').id); + await mod.processQueue(); + expect(mod.store.patientComment(1).markdown).toBe('Edited'); + }); + test('a check that throws, or answers wrongly, is an error outcome, and processing goes on', async () => { jest.spyOn(signatures, 'verify').mockRejectedValueOnce(new Error('canonicalization blew up')) .mockResolvedValueOnce([{ status: 'fatal', description: 'x' }, { status: 'information', keyId: null, description: 'fine' }]) @@ -4128,6 +4273,240 @@ describe('signing a document for download', () => { expect(r.status).toBe(422); expect(r.body.error).toBe('The document could not be signed: cannot canonicalize'); }); + + test('Include Patient Comments: only when there are some; old patient notes removed before signing, the comments added after', async () => { + const PN = { system: 'http://loinc.org', code: '51855-5' }; + // a document that already has a patient notes section + const withNotes = ips(); + withNotes.entry[0].resource.section.push({ title: 'Old notes', code: { coding: [PN] }, text: { status: 'generated', div: '
    old
    ' } }); + await post(app, 'demo', withNotes); + const copy = (body) => request(app).post('/ips/demo/Bundle/2/signed').set('Accept', 'application/fhir+json').send(body); + // no comments: no choice, and none to include + let page = await request(app).get('/ips/demo/Bundle/2?view=source').set('Accept', 'text/html'); + expect(page.text).not.toContain('Include Patient Comments'); + expect((await copy({ source: 'original', comments: true })).status).toBe(409); + mod.store.savePatientComment(2, 'That is **not** my diagnosis', 'Jane'); + page = await request(app).get('/ips/demo/Bundle/2?view=source').set('Accept', 'text/html'); + expect(page.text).toContain(' Include Patient Comments'); + + // comments alone: anyone, no signing + const spy = jest.spyOn(signatures, 'sign'); + let r = await copy({ source: 'original', comments: true }); + expect(r.status).toBe(200); + expect(spy).not.toHaveBeenCalled(); + let sections = r.body.entry[0].resource.section; + expect(sections.map(x => x.title)).toEqual(['Patient\'s Comments', 'Allergies and Intolerances', 'Medication Summary']); + expect(sections[0]).toEqual({ + title: 'Patient\'s Comments', code: { coding: [PN] }, author: [{ reference: 'urn:uuid:pat-1' }], + text: { status: 'additional', div: '

    That is not my diagnosis

    ' } + }); + // the stored document is not changed + expect(mod.store.read(2).bundle.entry[0].resource.section.map(x => x.title)).toEqual(['Allergies and Intolerances', 'Medication Summary', 'Old notes']); + + // signed too: sign() sees the document without any patient notes; the comments go in after + const admin = auth.principalById(auth.store.userByLogin('admin').id); + await keystore.create(admin, 'EC-P256', { system: true }); + spy.mockImplementationOnce(async (d) => ({ ...d, signature: [{ data: 'SIGNED' }] })); + r = await copy({ source: 'original', system: true, comments: true }); + expect(r.status).toBe(200); + const [given] = spy.mock.calls[0]; + expect(given.entry[0].resource.section.map(x => x.title)).toEqual(['Allergies and Intolerances', 'Medication Summary']); + expect(r.body.signature).toEqual([{ data: 'SIGNED' }]); + sections = r.body.entry[0].resource.section; + expect(sections.map(x => x.title)).toEqual(['Patient\'s Comments', 'Allergies and Intolerances', 'Medication Summary']); + }); + + test('Regenerate narrative: the narrative generated as the narrative step does it, before signing, after old patient notes go; comments after that', async () => { + let page = await request(app).get('/ips/demo/Bundle/1?view=source').set('Accept', 'text/html'); + expect(page.text).toContain(' Regenerate narrative'); + const copy = (body) => request(app).post('/ips/demo/Bundle/1/signed').set('Accept', 'application/fhir+json').send(body); + // on its own: anyone + let r = await copy({ source: 'original', narrative: true }); + expect(r.status).toBe(200); + const comp = r.body.entry[0].resource; + const stored = mod.store.read(1).bundle.entry[0].resource; + expect(comp.text.status).toBe('generated'); + expect(comp.text.div).not.toEqual(stored.text.div); + expect(comp.section[0].text.status).toBe('generated'); + expect(comp.section[0].text.div).toContain('Penicillin'); + // the same narrative the narrative step makes + const { generateNarrative } = require('../../ips/pipeline'); + const expected = structuredClone(mod.store.read(1).bundle); + await generateNarrative(expected, mod); + expect(r.body.entry[0].resource.text).toEqual(expected.entry[0].resource.text); + expect(stored.text.status).toBe('generated'); + expect(stored.text.div).toContain('Summary for Jane Smith'); + + // with signing and comments: sign() gets the regenerated narrative; the comments are not regenerated over + mod.store.savePatientComment(1, 'Mine', 'Jane'); + const admin = auth.principalById(auth.store.userByLogin('admin').id); + await keystore.create(admin, 'EC-P256', { system: true }); + const spy = jest.spyOn(signatures, 'sign'); + r = await copy({ source: 'original', narrative: true, system: true, comments: true }); + expect(r.status).toBe(200); + expect(spy.mock.calls[0][0].entry[0].resource.text).toEqual(expected.entry[0].resource.text); + const sections = r.body.entry[0].resource.section; + expect(sections[0].text).toEqual({ status: 'additional', div: '

    Mine

    ' }); + expect(sections[1].text.status).toBe('generated'); + }); +}); + +describe('the $document operation', () => { + const signatures = require('../../ips/signatures'); + const keystore = require('../../library/keystore'); + const zlib = require('zlib'); + let app; + let mod; + beforeEach(async () => { + ({ app, mod } = await makeApp()); + keystore.initialize({ database: ':memory:', privateDatabase: ':memory:' }, { log: quietLog, auth }); + auth.config.publicUrl = 'https://fhir.example.org'; + mod.store.createProject('demo', 'Demo', null); + await post(app, 'demo', ips()); + }); + afterEach(() => { + jest.restoreAllMocks(); + keystore.shutdown(); + mod.shutdown(); + }); + const op = (query = '', accept) => { + const r = request(app).get(`/ips/demo/Bundle/1/$document${query}`); + return accept ? r.set('Accept', accept) : r; + }; + // the files in a ZIP: name -> content + const unzip = (buf) => { + const files = {}; + let i = 0; + while (buf.readUInt32LE(i) === 0x04034b50) { + const size = buf.readUInt32LE(i + 18); + const nameLen = buf.readUInt16LE(i + 26); + const extra = buf.readUInt16LE(i + 28); + const name = buf.subarray(i + 30, i + 30 + nameLen).toString('utf8'); + const start = i + 30 + nameLen + extra; + files[name] = zlib.inflateRawSync(buf.subarray(start, start + size)).toString('utf8'); + i = start + size; + } + return files; + }; + const binary = (r) => r.buffer(true).parse((res, cb) => { + const chunks = []; + res.on('data', c => chunks.push(c)); + res.on('end', () => cb(null, Buffer.concat(chunks))); + }); + + test('the CapabilityStatement names it, with the OperationDefinition on GitHub; the OperationDefinition is there', async () => { + const cs = (await request(app).get('/ips/demo/metadata')).body; + expect(cs.rest[0].resource[0].operation).toEqual([{ name: 'document', definition: 'https://github.com/HealthIntersections/FHIRsmith/blob/main/ips/OperationDefinition-ips-document.json' }]); + const od = require('../../ips/OperationDefinition-ips-document.json'); + expect(od.url).toBe(cs.rest[0].resource[0].operation[0].definition); + expect(od.parameter.filter(p => p.use === 'in').map(p => p.name)).toEqual(['source', 'user-sign', 'system-sign', 'patient-notes', 'regenerate-narrative']); + // the source view says so, under its links + const page = await request(app).get('/ips/demo/Bundle/1?view=source').set('Accept', 'text/html'); + expect(page.text).toContain('with the $document operation: /ips/demo/Bundle/1/$document.

    '); + }); + + test('JSON by default (Accept, _format); the parameters are checked; 406 for what it does not give', async () => { + const stored = mod.store.read(1).bundle; + for (const r of [await op(), await op('', 'text/html,application/xhtml+xml,*/*;q=0.8'), await op('?_format=json'), await op('?_format=application/fhir+json'), await op('', 'application/json')]) { + expect(r.status).toBe(200); + expect(r.headers['content-type']).toMatch(/^application\/fhir\+json/); + expect(r.body).toEqual(stored); + } + expect((await op('?user-sign=yes')).status).toBe(400); + const r = await op('?colour=blue&source=both'); + expect(r.status).toBe(400); + expect(r.body.issue.map(i => i.details.text)).toEqual(['$document has no parameter \'colour\' (it takes source, user-sign, system-sign, patient-notes, regenerate-narrative)', 'source is original or modified, not \'both\'']); + expect((await op('', 'application/fhir+xml')).status).toBe(406); + expect((await op('?_format=xml')).status).toBe(406); + expect((await op('?source=modified')).status).toBe(409); + expect((await request(app).get('/ips/demo/Bundle/9/$document')).status).toBe(404); + // false is false + expect((await op('?patient-notes=false&system-sign=false')).body).toEqual(stored); + }); + + test('user-sign: an API token (not a session), and a key pair; system-sign: throttled as on the web page', async () => { + const spy = jest.spyOn(signatures, 'sign'); + let r = await op('?user-sign=true'); + expect(r.status).toBe(401); + expect(r.body.issue[0].details.text).toMatch(/needs an API token/); + // a session isn't an API token + const { agent } = await authLogin(app, 'admin', ADMIN_PASSWORD); + expect((await agent.get('/ips/demo/Bundle/1/$document?user-sign=true')).status).toBe(401); + const adminId = auth.store.userByLogin('admin').id; + const token = tokenFor(adminId); + r = await op('?user-sign=true').set('Authorization', `Bearer ${token}`); + expect(r.status).toBe(409); + expect(r.body.issue[0].details.text).toMatch(/You have no .* key pair/); + const admin = auth.principalById(adminId); + await keystore.create(admin, 'Ed25519'); + await keystore.create(admin, 'EC-P256', { system: true }); + r = await op('?user-sign=true').set('Authorization', `Bearer ${token}`); + expect(r.status).toBe(200); + expect(spy.mock.calls[0][1].user.identity).toEqual({ name: 'Administrator', login: 'admin', email: null }); + expect(spy.mock.calls[0][1].system).toBeNull(); + expect((await op('?system-sign=true')).status).toBe(200); + expect(spy.mock.calls[1][1].system).not.toBeNull(); + r = await op('?system-sign=true'); + expect(r.status).toBe(429); + expect(r.body.issue[0].code).toBe('throttled'); + }); + + test('patient-notes (nothing, silently, when there are none) and regenerate-narrative; POST with Parameters', async () => { + const stored = mod.store.read(1).bundle; + expect((await op('?patient-notes=true')).body).toEqual(stored); + mod.store.savePatientComment(1, 'Not *mine*', 'Jane'); + let r = await op('?patient-notes=true®enerate-narrative=true'); + expect(r.status).toBe(200); + const comp = r.body.entry[0].resource; + expect(comp.section[0]).toEqual({ + title: 'Patient\'s Comments', code: { coding: [{ system: 'http://loinc.org', code: '51855-5' }] }, author: [{ reference: 'urn:uuid:pat-1' }], + text: { status: 'additional', div: '

    Not mine

    ' } + }); + expect(comp.text.status).toBe('generated'); + expect(comp.text.div).not.toEqual(stored.entry[0].resource.text.div); + // POST: a Parameters resource + const p = await request(app).post('/ips/demo/Bundle/1/$document').set('Content-Type', 'application/fhir+json') + .send(JSON.stringify({ resourceType: 'Parameters', parameter: [{ name: 'patient-notes', valueBoolean: true }, { name: 'source', valueCode: 'original' }] })); + expect(p.status).toBe(200); + expect(JSON.parse(p.text).entry[0].resource.section[0].title).toBe('Patient\'s Comments'); + expect((await request(app).post('/ips/demo/Bundle/1/$document').set('Content-Type', 'application/fhir+json').send('{"resourceType":"Bundle"}')).status).toBe(400); + }); + + test('a ZIP and a PDF, made on the server, with the document in them', async () => { + mod.store.savePatientComment(1, 'Mine', 'Jane'); + let r = await binary(op('?patient-notes=true', 'application/zip')); + expect(r.status).toBe(200); + expect(r.headers['content-type']).toBe('application/zip'); + expect(r.headers['content-disposition']).toBe('attachment; filename="ips-demo-1.zip"'); + const files = unzip(r.body); + expect(Object.keys(files)).toEqual(['ips-demo-1.json']); + expect(JSON.parse(files['ips-demo-1.json']).entry[0].resource.section[0].title).toBe('Patient\'s Comments'); + expect(unzip((await binary(op('?_format=zip'))).body)['ips-demo-1.json']).toBe(JSON.stringify(mod.store.read(1).bundle, null, 2)); + + r = await binary(op('', 'application/pdf')); + expect(r.status).toBe(200); + expect(r.headers['content-type']).toBe('application/pdf'); + expect(r.headers['content-disposition']).toBe('attachment; filename="ips-demo-1.pdf"'); + expect(r.body.subarray(0, 5).toString()).toBe('%PDF-'); + expect(r.body.toString('latin1')).toContain('(ips-demo-1.json)'); + const { PDFDocument } = require('../../ips/vendor/pdf-lib.min.js'); + expect((await PDFDocument.load(r.body)).getPageCount()).toBe(1); + }); + + test('the PDF says what the browser\'s says: title, patient, date, each section\'s narrative', async () => { + const { pdfContent, narrativeLines } = require('../../ips/export'); + expect(pdfContent(mod.store.read(1).bundle)).toEqual([ + { text: 'Patient Summary as of 1 March 2026', kind: 'h1' }, + { text: 'Jane Alexandra Smith, born 1970-05-06, female', kind: 'b' }, + { text: 'Date: 2026-03-01T09:30:00Z', kind: 'p' }, + { text: 'Allergies and Intolerances', kind: 'h2' }, + { text: 'Penicillin', kind: 'p' }, + { text: 'Medication Summary', kind: 'h2' }, + { text: 'No known medications', kind: 'p' } + ]); + expect(narrativeLines('

    H

    • a
    AB
    12
    ')) + .toEqual([{ text: 'H', bold: true }, { text: '• a', bold: false }, { text: 'A | B', bold: true }, { text: '1 | 2', bold: false }]); + }); }); describe('signing and checking: the safeguards', () => { diff --git a/tests/ips/patient-comments.test.js b/tests/ips/patient-comments.test.js new file mode 100644 index 00000000..790731ac --- /dev/null +++ b/tests/ips/patient-comments.test.js @@ -0,0 +1,74 @@ +const { removePatientNotes, addPatientComments, markdownHtmlParts, markdownHtml, htmlToMarkdown, patientNotesMarkdown } = require('../../ips/patient-comments'); + +const notes = (title) => ({ title, code: { coding: [{ system: 'http://loinc.org', code: '51855-5' }] }, text: { status: 'generated', div: '
    old
    ' } }); +const allergies = { title: 'Allergies', code: { coding: [{ system: 'http://loinc.org', code: '48765-2' }] } }; + +function doc(sections, subject = { reference: 'urn:uuid:pat-1' }) { + return { + resourceType: 'Bundle', type: 'document', + entry: [ + { fullUrl: 'urn:uuid:comp-1', resource: { resourceType: 'Composition', ...(subject ? { subject } : {}), ...(sections ? { section: sections } : {}) } }, + { fullUrl: 'urn:uuid:pat-1', resource: { resourceType: 'Patient' } } + ] + }; +} + +describe('patient comments in a document', () => { + test('existing patient notes sections are removed, at any depth; the document passed in is not changed', () => { + const d = doc([notes('a'), { ...allergies, section: [notes('nested'), { title: 'kept' }] }]); + const before = structuredClone(d); + const out = removePatientNotes(d); + expect(d).toEqual(before); + expect(out.entry[0].resource.section).toEqual([{ ...allergies, section: [{ title: 'kept' }] }]); + expect(removePatientNotes(doc([notes('only')])).entry[0].resource.section).toBeUndefined(); + expect(removePatientNotes(doc(null))).toEqual(doc(null)); + }); + + test('the comments go in as the first section: code, title, the patient as author, the narrative (additional) - nothing else', () => { + const d = doc([allergies]); + const out = addPatientComments(d, 'I **never** had asthma.\n\n- see '); + expect(d.entry[0].resource.section).toEqual([allergies]); + expect(out.entry[0].resource.section).toEqual([ + { + title: 'Patient\'s Comments', + code: { coding: [{ system: 'http://loinc.org', code: '51855-5' }] }, + author: [{ reference: 'urn:uuid:pat-1' }], + text: { + status: 'additional', + div: '

    I never had asthma.

    \n
    ' + } + }, + allergies + ]); + // no sections before; no subject: the Patient entry's fullUrl + const plain = addPatientComments(doc(null, null), 'x').entry[0].resource.section; + expect(plain.length).toBe(1); + expect(plain[0].author).toEqual([{ reference: 'urn:uuid:pat-1' }]); + expect(() => addPatientComments({ resourceType: 'Bundle', entry: [] }, 'x')).toThrow(/no Composition/); + }); + + test('markdown: HTML is found (blocks, inline, comments), autolinks and < are not; rendering drops raw HTML', () => { + expect(markdownHtmlParts('a b')).toEqual(['', '']); + expect(markdownHtmlParts('
    \nx\n
    ').length).toBe(1); + expect(markdownHtmlParts('').length).toBe(1); + expect(markdownHtmlParts('see and 2 < 3')).toEqual([]); + expect(markdownHtml('a ')).not.toContain('