diff --git a/snprc_ehr/resources/etls/BiocontainmentObservations.xml b/snprc_ehr/resources/etls/BiocontainmentObservations.xml index e6e0aa124..0450518bc 100644 --- a/snprc_ehr/resources/etls/BiocontainmentObservations.xml +++ b/snprc_ehr/resources/etls/BiocontainmentObservations.xml @@ -14,6 +14,11 @@ + + + + diff --git a/snprc_ehr/resources/queries/study/BiocontainmentObservations.js b/snprc_ehr/resources/queries/study/BiocontainmentObservations.js new file mode 100644 index 000000000..9ed999135 --- /dev/null +++ b/snprc_ehr/resources/queries/study/BiocontainmentObservations.js @@ -0,0 +1,176 @@ +/* + * Copyright (c) 2026 SNPRC + */ +require("ehr/triggers").initScript(this); + +// The 13 scored parameters on TXB 904-1 — each carries its own reason comment (9/1 decision 7) +var SCORED_FIELDS = ['WeightLoss', 'TemperatureChange', 'Responsiveness', 'HairCoat', 'Respiration', 'Petechia', + 'Bleeding', 'NasalDischarge', 'FeedEaten', 'FoodEnrichment', 'Stool', 'FluidIntake', 'Dehydration']; + +// Carry-over shares its parameter's reason column, so a carry-over change counts as a change to that parameter +var CARRY_OVER = {WeightLoss: 'WeightLossCO', TemperatureChange: 'TemperatureChangeCO', Petechia: 'PetechiaCO', + FeedEaten: 'FeedEatenCO', FoodEnrichment: 'FoodEnrichmentCO', Dehydration: 'DehydrationCO'}; + +var REVIEW_REQUIRED = 'Review Required'; +var COMPLETED = 'Completed'; + +function sameValue(a, b){ + return (a == null ? null : String(a)) === (b == null ? null : String(b)); +} + +// Trimmed text, with empty and blank both meaning "no value" +function trimmed(value){ + var text = value == null ? '' : String(value).trim(); + return text === '' ? null : text; +} + +function sameNumber(a, b){ + return (a == null || a === '' || b == null || b === '') ? sameValue(a, b) : Number(a) === Number(b); +} + +function sameCarryOver(a, b){ + return !!Number(a) === !!Number(b); +} + +// Milliseconds for a date, a Java date, or LabKey's 'yyyy-MM-dd HH:mm:ss.SSS' string; NaN if it can't be read. +// Rhino 1.7R3 can't parse that string, and new Date(javaDate) drops the milliseconds, so neither is used. +function toMillis(value){ + if (value == null) + return NaN; + if (typeof value.getTime === 'function') + return Number(value.getTime()); + var m = /^(\d{4})[-\/](\d{1,2})[-\/](\d{1,2})[ T](\d{1,2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?/.exec(String(value)); + if (!m) + return NaN; + var ms = m[7] ? Number((m[7] + '00').substring(0, 3)) : 0; + return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6] || 0), ms).getTime(); +} + +function changedFields(row, oldRow){ + return SCORED_FIELDS.filter(function(field){ + var co = CARRY_OVER[field]; + return !sameValue(row[field], oldRow[field]) || (co && !sameCarryOver(row[co], oldRow[co])); + }); +} + +// Compared to the second: EHR drops the milliseconds from row.date before this trigger runs, but oldRow.date keeps them +function sameDate(a, b){ + var x = toMillis(a), y = toMillis(b); + return isNaN(x) || isNaN(y) ? sameValue(a, b) : Math.floor(x / 1000) === Math.floor(y / 1000); +} + +// Everything else the approver signed for: the animal, date, location, comment and every reason +function recordChanged(row, oldRow){ + return trimmed(row.Id) !== trimmed(oldRow.Id) + || !sameDate(row.date, oldRow.date) + || !sameNumber(row.Location, oldRow.Location) + || trimmed(row.Comment) !== trimmed(oldRow.Comment) + || SCORED_FIELDS.some(function(field){ + return trimmed(row[field + 'Comments']) !== trimmed(oldRow[field + 'Comments']); + }); +} + +var SIGNATURE_FIELDS = ['reviewedBy', 'reviewedByName', 'reviewedDate', 'reviewMeaning']; + +// Copies the signature from another row, or clears it when from is null +function setSignature(row, from){ + SIGNATURE_FIELDS.forEach(function(f){ + row[f] = from ? from[f] : null; + }); +} + +function clearReview(row){ + row.QCStateLabel = REVIEW_REQUIRED; + setSignature(row, null); +} + +// Every scored parameter on the form must have a value (LabKey checks this as well as CAMP) +function requireValues(scriptErrors, row){ + SCORED_FIELDS.forEach(function(field){ + if (row[field] == null || row[field] === '') + EHR.Server.Utils.addError(scriptErrors, field, 'A value is required for ' + field, 'ERROR'); + }); +} + +function onInsert(helper, scriptErrors, row){ + requireValues(scriptErrors, row); + clearReview(row); +} + +function onUpdate(helper, scriptErrors, row, oldRow){ + var changed = changedFields(row, oldRow); + // These need no reason of their own (the comment is free text, and a reason explains itself), + // but changing any of them is still a modification to approve + var otherChange = recordChanged(row, oldRow); + + if (helper.isETL()){ + // A re-merge with identical values (e.g. after the write-back export) must not undo an approval + if (changed.length || otherChange) + clearReview(row); + else + row.QCStateLabel = oldRow.QCStateLabel; + return; + } + + requireValues(scriptErrors, row); + + if (changed.length || otherChange){ + // An approval must never quietly become "not approved": the reviewer is told, whether the change is real or a bug + if (row.QCStateLabel === COMPLETED && oldRow.QCStateLabel !== COMPLETED){ + EHR.Server.Utils.addError(scriptErrors, 'QCStateLabel', 'This observation has changes that must be saved before it can be approved.', 'ERROR'); + return; + } + + // Trimmed, so a reason of only spaces is no reason, the same rule the page applies + changed.forEach(function(field){ + var reason = trimmed(row[field + 'Comments']); + if (!reason) + EHR.Server.Utils.addError(scriptErrors, field + 'Comments', 'A reason is required for each changed value', 'ERROR'); + else if (reason === trimmed(oldRow[field + 'Comments'])) + EHR.Server.Utils.addError(scriptErrors, field + 'Comments', 'Enter a new reason; this one was given for an earlier change', 'ERROR'); + else + row[field + 'Comments'] = reason; + }); + + // The approver approves the record and any modification (9/1 decision 6) + clearReview(row); + return; + } + + // Not approved (sent back for review by hand, or any other state): the old signature no longer applies + if (row.QCStateLabel !== COMPLETED){ + setSignature(row, null); + return; + } + + // Already approved and still approved: the signature can't be edited + if (oldRow.QCStateLabel === COMPLETED){ + setSignature(row, oldRow); + return; + } + + // Approval: the only place the signature is set + + // The reviewer must have seen the version being approved; EHR fills in modified, so it is sent under its own name + var viewed = toMillis(row.viewedModified); + if (isNaN(viewed) || viewed !== toMillis(oldRow.modified)){ + EHR.Server.Utils.addError(scriptErrors, 'QCStateLabel', 'This observation changed after you opened it. Check the current version and approve again.', 'ERROR'); + return; + } + + var user = LABKEY.Security.currentUser; + + if (sameValue(user.id, oldRow.createdBy)){ + EHR.Server.Utils.addError(scriptErrors, 'QCStateLabel', 'This observation must be reviewed by someone other than its author', 'ERROR'); + return; + } + + // Printed name for the signature record (REQ-028), read in Java so approvers don't need permission to see user details + var triggerHelper = new org.labkey.snprc_ehr.query.SNPRC_EHRTriggerHelper(user.id, LABKEY.Security.currentContainer.id); + var printedName = String(triggerHelper.getPrintedName()); + + row.reviewedBy = user.id; + row.reviewedByName = printedName; + row.reviewedDate = new Date(); + row.reviewMeaning = 'Reviewed and approved'; +} \ No newline at end of file diff --git a/snprc_ehr/resources/queries/study/BiocontainmentObservations.query.xml b/snprc_ehr/resources/queries/study/BiocontainmentObservations.query.xml index 8a2b704a5..d36ec9a90 100644 --- a/snprc_ehr/resources/queries/study/BiocontainmentObservations.query.xml +++ b/snprc_ehr/resources/queries/study/BiocontainmentObservations.query.xml @@ -8,6 +8,15 @@ + + MM/dd/yyyy HH:mm + + + MM/dd/yyyy HH:mm + + + MM/dd/yyyy HH:mm + true diff --git a/snprc_ehr/resources/queries/study/BiocontainmentObservations/Review.qview.xml b/snprc_ehr/resources/queries/study/BiocontainmentObservations/Review.qview.xml new file mode 100644 index 000000000..504e75ebe --- /dev/null +++ b/snprc_ehr/resources/queries/study/BiocontainmentObservations/Review.qview.xml @@ -0,0 +1,14 @@ + \ No newline at end of file diff --git a/snprc_ehr/resources/referenceStudy/study/datasets/datasets_metadata.xml b/snprc_ehr/resources/referenceStudy/study/datasets/datasets_metadata.xml index e59ff1ff9..3cc0b2647 100644 --- a/snprc_ehr/resources/referenceStudy/study/datasets/datasets_metadata.xml +++ b/snprc_ehr/resources/referenceStudy/study/datasets/datasets_metadata.xml @@ -3367,6 +3367,29 @@ 80 Comment + + integer + Reviewed By + + core + Users + UserId + + + + varchar + 128 + Reviewer Printed Name + + + timestamp + Reviewed Date + + + varchar + 64 + Signature Meaning + diff --git a/snprc_ehr/resources/views/begin.html b/snprc_ehr/resources/views/begin.html index 9b2545e92..88512996a 100644 --- a/snprc_ehr/resources/views/begin.html +++ b/snprc_ehr/resources/views/begin.html @@ -178,7 +178,17 @@ { name: 'Enter Data', url: '<%=contextPath%>' + ctx['EHRStudyContainer'] + '/ehr-enterData.view' }, ] - } + }, + { + header: 'Biocontainment', + itemDefaults: { + linkCls: 'none', + style: 'font-weight: bold;' + }, + items: [ + { name: 'Biocontainment Observation Review', url: '<%=contextPath%>' + ctx['EHRStudyContainer'] + '/snprc_ehr-BiocontainmentObservationReview.view' } + ] + } ] }; diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/BiocontainmentObservationReview.tsx b/snprc_ehr/src/client/BiocontainmentObservationReview/BiocontainmentObservationReview.tsx new file mode 100644 index 000000000..0b8bf1124 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/BiocontainmentObservationReview.tsx @@ -0,0 +1,136 @@ +import React, { useEffect, useRef, useState } from 'react'; +import { ActionURL } from '@labkey/api'; +import { Alert } from '@labkey/components'; +import { Col, Row } from 'react-bootstrap'; +import { approveObservation, fetchObservation, ObservationRow } from './api/observation'; +import { Reload, ReviewGridPanel } from './components/ReviewGridPanel'; +import ObservationDetail from './components/ObservationDetail'; +import { errorText } from './services/errorText'; +import { missingFields } from './constants/fields'; +import './styles/biocontainmentObservationReview.scss'; + +const MESSAGE_TIMEOUT_MS = 30000; + +// Default dataset grid filtered to observations approved in the last 7 days, newest first +const RECENTLY_APPROVED_URL = ActionURL.buildURL('query', 'executeQuery', undefined, { + schemaName: 'study', + 'query.queryName': 'BiocontainmentObservations', + 'query.QCState/Label~eq': 'Completed', + 'query.reviewedDate~dategte': '-7d', + 'query.sort': '-reviewedDate', +}); + +const BiocontainmentObservationReview = () => { + const [reload, setReload] = useState({ key: 0, clearSelections: false }); + const [focusedLsid, setFocusedLsid] = useState(); + const [focused, setFocused] = useState(); + const [message, setMessage] = useState(''); + const [error, setError] = useState(''); + const [isEditing, setIsEditing] = useState(false); + const messageTimer = useRef(); + + // Success messages clear themselves; errors stay until the next action + const showMessage = (text: string) => { + window.clearTimeout(messageTimer.current); + setMessage(text); + messageTimer.current = window.setTimeout(() => setMessage(''), MESSAGE_TIMEOUT_MS); + }; + + useEffect(() => () => window.clearTimeout(messageTimer.current), []); + + const reloadGrid = (clearSelections: boolean) => setReload(r => ({ key: r.key + 1, clearSelections })); + + useEffect(() => { + if (!focusedLsid) { + return; + } + // A slower fetch for a record that has since been approved or deselected must not reopen it + let isCurrent = true; + fetchObservation(focusedLsid) + .then(row => isCurrent && setFocused(row)) + .catch(e => isCurrent && setError(errorText(e))); + return () => { + isCurrent = false; + }; + }, [focusedLsid, reload]); + + const record = focused && focused.lsid === focusedLsid ? focused : undefined; + // The server rejects these approvals, so don't offer them: a missing value must be corrected first, + // and without the version on screen the server can't confirm the reviewer saw the current record + const canApprove = !!record && !isEditing && !!record.modified && missingFields(record).length === 0; + + const onApprove = async (lsid: string) => { + // Approve only the record on screen, at the version the reviewer saw + if (!canApprove || record.lsid !== lsid) return; + setError(''); + try { + await approveObservation(lsid, record.modified); + // Approved records leave the queue; close the record immediately rather than waiting for the grid to clear + setFocusedLsid(undefined); + showMessage('Observation approved.'); + reloadGrid(true); + } catch (e) { + // Author-as-approver, missing-role and changed-since-opened rejections arrive here from the server. + // A record that changed is out of date on screen, so fetch the current version; reloading after the others is harmless. + setError(errorText(e)); + reloadGrid(false); + } + }; + + // An error belongs to the record it came from, so selecting another record clears it; + // reloading the same record keeps it (e.g. "changed after you opened it") + const onFocus = (lsid: string | undefined) => { + if (lsid !== focusedLsid) setError(''); + setFocusedLsid(lsid); + }; + + const onSaved = () => { + setError(''); + showMessage('Correction saved. The observation needs approval again.'); + reloadGrid(false); + }; + + return ( +
+ + +

+ Select an observation to see the full record. Approve only observations you have checked. +

+ + {message} + + {error} + +
+ + + + + + {record ? ( + + ) : ( +

+ ☑ Select an observation to see the full record. +

+ )} + +
+ + + + View observations approved in the last 7 days. + + + +
+ ); +}; + +export default BiocontainmentObservationReview; diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/api/observation.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/api/observation.ts new file mode 100644 index 000000000..423c95c62 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/api/observation.ts @@ -0,0 +1,129 @@ +import { ActionURL, Filter, Query } from '@labkey/api'; +import { carryOverOf, COMPLETED, SCORED_FIELDS } from '../constants/fields'; + +const SCHEMA = 'study'; +const QUERY = 'BiocontainmentObservations'; + +const COLUMNS = [ + 'lsid', + 'Id', + 'date', + 'Location', + 'Comment', + 'QCState/Label', + 'createdBy', + 'createdBy/DisplayName', + 'created', + 'modifiedBy/DisplayName', + 'modified', +].concat(...SCORED_FIELDS.map(f => [f.name, `${f.name}Comments`].concat(f.carryOver ? [f.carryOver] : []))); + +// The fixed columns are named; scored values, reasons and carry-overs are read by name from SCORED_FIELDS +export interface ObservationRow { + [field: string]: any; + Comment?: string; + created?: string; + createdBy?: number; + 'createdBy/DisplayName'?: string; + date: string; + Id: string; + Location: number | string; + lsid: string; + modified?: string; + 'modifiedBy/DisplayName'?: string; + 'QCState/Label'?: string; +} + +export const fetchObservation = (lsid: string): Promise => + new Promise((resolve, reject) => { + Query.selectRows({ + schemaName: SCHEMA, + queryName: QUERY, + columns: COLUMNS, + filterArray: [Filter.create('lsid', lsid)], + success: data => resolve(data.rows[0]), + failure: reject, + }); + }); + +// Sends the version the reviewer saw; the trigger rejects the approval if the record has changed since +export const approveObservation = (lsid: string, viewedModified: string): Promise => + new Promise((resolve, reject) => { + // Without it the trigger can only report "changed after you opened it", which would be wrong + if (!viewedModified) { + reject({ + exception: + 'This observation could not be approved because its version is unknown. Reload the page and try again.', + }); + return; + } + Query.updateRows({ + schemaName: SCHEMA, + queryName: QUERY, + rows: [{ lsid, QCStateLabel: COMPLETED, viewedModified }], + success: resolve, + failure: reject, + }); + }); + +export interface Correction { + carryOver?: number; + field: string; + reason: string; + value: any; +} + +// comment is only sent when it changed; an empty comment clears it +export const correctObservation = (lsid: string, corrections: Correction[], comment?: string): Promise => { + const row: Record = { lsid }; + if (comment !== undefined) row.Comment = comment === '' ? null : comment; + corrections.forEach(c => { + row[c.field] = c.value; + row[`${c.field}Comments`] = c.reason; + const co = carryOverOf(c.field); + if (co && c.carryOver !== undefined) row[co] = c.carryOver; + }); + return new Promise((resolve, reject) => { + Query.updateRows({ + schemaName: SCHEMA, + queryName: QUERY, + rows: [row], + success: resolve, + failure: reject, + }); + }); +}; + +// Same animal, same location. Any QC state: the tech saw the prior whether or not it had been approved. +const historyFilters = (row: Pick) => [ + Filter.create('Id', row.Id), + Filter.create('Location', row.Location), +]; + +// Most recent observation before this one +export const fetchPriorObservation = ( + row: Pick +): Promise => + new Promise((resolve, reject) => { + Query.selectRows({ + schemaName: SCHEMA, + queryName: QUERY, + columns: COLUMNS, + // LESS_THAN, not DATE_LESS_THAN: the date filter drops the time, and an animal can have two observations in a day + filterArray: historyFilters(row).concat(Filter.create('date', row.date, Filter.Types.LESS_THAN)), + sort: '-date', + maxRows: 1, + success: data => resolve(data.rows[0]), + failure: reject, + }); + }); + +// Full history for the animal at this location, newest first +export const historyUrl = (row: Pick): string => + ActionURL.buildURL('query', 'executeQuery', undefined, { + schemaName: SCHEMA, + 'query.queryName': QUERY, + 'query.Id~eq': row.Id, + 'query.Location~eq': row.Location, + 'query.sort': '-date', + }); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/app.tsx b/snprc_ehr/src/client/BiocontainmentObservationReview/app.tsx new file mode 100644 index 000000000..f623c0176 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/app.tsx @@ -0,0 +1,10 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; + +import BiocontainmentObservationReview from './BiocontainmentObservationReview'; + +// Need to wait for container element to be available in labkey wrapper before render +window.addEventListener('DOMContentLoaded', () => { + // eslint-disable-next-line react/no-deprecated -- this module is on React 16, which has no createRoot + ReactDOM.render(, document.getElementById('app')); +}); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/components/ObservationDetail.tsx b/snprc_ehr/src/client/BiocontainmentObservationReview/components/ObservationDetail.tsx new file mode 100644 index 000000000..d96f5cece --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/components/ObservationDetail.tsx @@ -0,0 +1,237 @@ +import React, { useEffect, useState } from 'react'; +import { Button, OverlayTrigger, Tooltip } from 'react-bootstrap'; +import { Correction, correctObservation, fetchPriorObservation, historyUrl, ObservationRow } from '../api/observation'; +import { formatDateTime } from '../services/formatDate'; +import { clinicalScore, displayScore } from '../services/clinicalScore'; +import { carryOverOf, isMissingValue, missingFields, SCORED_FIELDS } from '../constants/fields'; +import { errorText } from '../services/errorText'; + +interface Props { + onEditingChange: (editing: boolean) => void; + onSaved: () => void; + row: ObservationRow; +} + +const priorTooltip = View prior observation history; + +const ObservationDetail = ({ row, onSaved, onEditingChange }: Props) => { + const [isEditing, setIsEditing] = useState(false); + const [edits, setEdits] = useState>({}); + const [errorMessage, setErrorMessage] = useState(''); + const [prior, setPrior] = useState(); + // undefined until the comment is edited + const [comment, setComment] = useState(); + + // A carry-over shares its parameter's reason, so changing either one needs it. Empty and 0 both mean No. + const sameCarryOver = (a: any, b: any) => !!Number(a) === !!Number(b); + const isChanged = (e: Correction) => { + const co = carryOverOf(e.field); + return String(e.value) !== String(row[e.field]) || (co !== undefined && !sameCarryOver(e.carryOver, row[co])); + }; + const changed = Object.values(edits).filter(isChanged); + const isMissing = (field: string) => isMissingValue(row[field]); + // A reason must be new: the stored one belongs to an earlier change + const missingReason = changed.filter( + e => !e.reason?.trim() || e.reason.trim() === (row[`${e.field}Comments`] ?? '') + ); + // The comment is free text, so it is its own reason; changing it still sends the record back for approval + const commentChanged = comment !== undefined && comment.trim() !== (row.Comment ?? ''); + const hasChanges = changed.length > 0 || commentChanged; + + // The score follows unsaved edits, as the tablet's does while values are picked + const edited = Object.values(edits).reduce((r, e) => ({ ...r, [e.field]: e.value }), row); + // The server rejects a save while any value is still missing, even one the reviewer didn't touch + const stillMissing = missingFields(edited); + + // A correction reloads the row but never moves it, so the prior only changes with the animal, location or date + useEffect(() => { + let isCurrent = true; + fetchPriorObservation(row) + .then(p => isCurrent && setPrior(p)) + .catch(e => isCurrent && setErrorMessage(errorText(e, 'Could not load the prior observation'))); + return () => { + isCurrent = false; + }; + // eslint-disable-next-line react-hooks/exhaustive-deps -- the prior only depends on animal, location and date + }, [row.Id, row.Location, row.date]); + + // The page disables Approve while a correction is open; the cleanup re-enables it when the record closes + useEffect(() => { + onEditingChange(isEditing); + return () => onEditingChange(false); + // eslint-disable-next-line react-hooks/exhaustive-deps -- onEditingChange is a state setter + }, [isEditing]); + + const setEdit = (field: string, patch: Partial) => { + const co = carryOverOf(field); + setEdits({ + ...edits, + [field]: { + field, + value: row[field], + carryOver: co ? row[co] : undefined, + reason: '', + ...edits[field], + ...patch, + }, + }); + }; + + const onSave = async () => { + setErrorMessage(''); + try { + await correctObservation(row.lsid, changed, commentChanged ? comment.trim() : undefined); + setEdits({}); + setComment(undefined); + setIsEditing(false); + onSaved(); + } catch (error) { + setErrorMessage(errorText(error, 'Save failed')); + } + }; + + return ( +
+
+ {row.Id} · Location {row.Location} · {formatDateTime(row.date)} +
+
+

Recorded by {row['createdBy/DisplayName']}

+ + + + + {/* Hidden when there is no prior, as on the tablet */} + {prior && ( + + )} + + + + + + + {SCORED_FIELDS.map(f => ( + + + {prior && } + + + + + ))} + +
Parameter + + + Prior + + + ValueCarry overReason for change
{f.label}{prior[f.name] ?? '-'} + {isEditing ? ( + + ) : isMissing(f.name) ? ( + Missing + ) : ( + row[f.name] + )} + + {f.carryOver && + (isEditing ? ( + + ) : row[f.carryOver] ? ( + 'Yes' + ) : ( + 'No' + ))} + e.field === f.name) ? 'needs-reason' : undefined} + > + {isEditing ? ( + setEdit(f.name, { reason: e.target.value })} + value={edits[f.name]?.reason ?? ''} + /> + ) : ( + row[`${f.name}Comments`] + )} +
+ {/* Calculated from the values above, never entered */} +

+ Clinical Score: {displayScore(clinicalScore(edited))} + {prior && (prior {displayScore(clinicalScore(prior))})} +

+ {isEditing ? ( +
+ + setComment(e.target.value)} + value={comment ?? row.Comment ?? ''} + /> +
+ ) : ( +

Comment: {row.Comment}

+ )} + {isEditing && stillMissing.length > 0 && ( +

+ Fill in every missing value before saving: {stillMissing.map(f => f.label).join(', ')}. +

+ )} + {errorMessage &&

{errorMessage}

} + {isEditing ? ( + <> + + + + ) : ( + + )} +
+
+ ); +}; + +export default ObservationDetail; diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/components/ReviewGridPanel.tsx b/snprc_ehr/src/client/BiocontainmentObservationReview/components/ReviewGridPanel.tsx new file mode 100644 index 000000000..de6725a1f --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/components/ReviewGridPanel.tsx @@ -0,0 +1,112 @@ +import React, { FC, memo, useEffect, useMemo } from 'react'; +import { Filter } from '@labkey/api'; +import { + GridPanel, + InjectedQueryModels, + QueryConfigMap, + RequiresModelAndActions, + withQueryModels, +} from '@labkey/components'; +import { Button } from 'react-bootstrap'; +import { REVIEW_REQUIRED } from '../constants/fields'; +import { OBSERVATION_REVIEW } from '../schemas'; + +const MODEL_ID = 'observationReview'; + +export interface Reload { + clearSelections: boolean; + key: number; +} + +interface Props { + canApprove: boolean; + onApprove: (lsid: string) => void; + onFocus: (lsid: string) => void; + reload: Reload; +} + +interface ButtonProps { + canApprove: boolean; + onApprove: (lsid: string) => void; +} + +// Approval is one observation at a time; bulk approval is off +const ApproveButton: FC = ({ canApprove, model, onApprove }) => { + const lsid = model.selections?.size === 1 ? Array.from(model.selections)[0] : undefined; + return ( +
+ +
+ ); +}; + +const ReviewGridPanelImpl: FC = memo(function ReviewGridPanelImpl({ + actions, + canApprove, + queryModels, + reload, + onApprove, + onFocus, +}) { + const model = queryModels[MODEL_ID]; + + // Approved rows leave the queue, so their selections must go too; a correction keeps the row and the detail pane open. + // Loading selections in parallel with the clear can restore the approved row's selection, so skip it when clearing. + useEffect(() => { + if (!reload.key) return; + if (reload.clearSelections) actions.clearSelections(MODEL_ID); + actions.loadModel(MODEL_ID, !reload.clearSelections, true); + }, [reload]); + + // Single selection, as in SndLookupsManagement's TableGridPanel: ticking a second row replaces the first. + // The detail pane follows the one selected row. + useEffect(() => { + const selected = model?.selections ? Array.from(model.selections) : []; + if (selected.length > 1) { + actions.replaceSelections(MODEL_ID, [selected[selected.length - 1]]); + return; + } + onFocus(selected[0]); + }, [model.selections]); + + return ( + + ); +}); + +const ReviewGridPanelWithQueryModels = withQueryModels(ReviewGridPanelImpl); + +export const ReviewGridPanel: FC = memo(function ReviewGridPanel(props) { + const queryConfigs = useMemo( + () => ({ + [MODEL_ID]: { + id: MODEL_ID, + schemaQuery: OBSERVATION_REVIEW, + baseFilters: [Filter.create('QCState/Label', REVIEW_REQUIRED)], + // Without this the total count is never requested, and the selection status spins forever + includeTotalCount: true, + maxRows: 100, + }, + }), + [] + ); + + return ; +}); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/constants/fields.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/constants/fields.ts new file mode 100644 index 000000000..6c10c123a --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/constants/fields.ts @@ -0,0 +1,34 @@ +export interface ScoredField { + carryOver?: string; + label: string; + name: string; + values: (number | string)[]; +} + +// Order follows TXB 904-1; values from the CK_* constraints in createBiocontainmentObservation.sql +export const SCORED_FIELDS: ScoredField[] = [ + { name: 'WeightLoss', label: 'Weight Loss', carryOver: 'WeightLossCO', values: [0, 1, 2] }, + { name: 'TemperatureChange', label: 'Temperature Change', carryOver: 'TemperatureChangeCO', values: [0, 1, 2, 3] }, + { name: 'Responsiveness', label: 'Responsiveness', values: [0, 1, 2, 8, 15] }, + { name: 'HairCoat', label: 'Hair Coat', values: [0, 1] }, + { name: 'Respiration', label: 'Respiration', values: [0, 8, 15] }, + { name: 'Petechia', label: 'Petechia', carryOver: 'PetechiaCO', values: [0, 1, 2, 3] }, + { name: 'Bleeding', label: 'Bleeding', values: [0, 1, 2] }, + { name: 'NasalDischarge', label: 'Nasal Discharge', values: [0, 1] }, + { name: 'FeedEaten', label: 'Feed Eaten', carryOver: 'FeedEatenCO', values: [0, 1] }, + { name: 'FoodEnrichment', label: 'Food Enrichment', carryOver: 'FoodEnrichmentCO', values: [0, 1] }, + { name: 'Stool', label: 'Stool', values: ['0', '1', '2D', '2R'] }, + { name: 'FluidIntake', label: 'Fluid Intake', values: [0, 1, 2] }, + { name: 'Dehydration', label: 'Dehydration', carryOver: 'DehydrationCO', values: [0, 1] }, +]; + +export const carryOverOf = (field: string): string | undefined => SCORED_FIELDS.find(f => f.name === field)?.carryOver; + +export const isMissingValue = (value: unknown): boolean => value == null || value === ''; + +// Scored parameters with no value; the trigger rejects any save or approval until each one is filled in +export const missingFields = (row: Record): ScoredField[] => + SCORED_FIELDS.filter(f => isMissingValue(row[f.name])); + +export const REVIEW_REQUIRED = 'Review Required'; +export const COMPLETED = 'Completed'; diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/dev.tsx b/snprc_ehr/src/client/BiocontainmentObservationReview/dev.tsx new file mode 100644 index 000000000..70e84a92c --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/dev.tsx @@ -0,0 +1,11 @@ +import React from 'react'; +import ReactDOM from 'react-dom'; + +import BiocontainmentObservationReview from './BiocontainmentObservationReview'; + +const render = () => { + // eslint-disable-next-line react/no-deprecated -- this module is on React 16, which has no createRoot + ReactDOM.render(, document.getElementById('app')); +}; + +render(); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/schemas.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/schemas.ts new file mode 100644 index 000000000..8b53dff42 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/schemas.ts @@ -0,0 +1,3 @@ +import { SchemaQuery } from '@labkey/components'; + +export const OBSERVATION_REVIEW = new SchemaQuery('study', 'BiocontainmentObservations', 'Review'); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/services/clinicalScore.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/services/clinicalScore.ts new file mode 100644 index 000000000..c664bcfb6 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/services/clinicalScore.ts @@ -0,0 +1,21 @@ +import { SCORED_FIELDS } from '../constants/fields'; + +// Mirrors Observation.scoreOf() in ASI-ObsSingle and the CAMP edit screen: Stool "2D"/"2R" scores 2 +export const scoreOf = (value: any): number | undefined => { + if (value === null || value === undefined || value === '') return undefined; + const score = parseInt(String(value), 10); + return isNaN(score) ? undefined : score; +}; + +// Mirrors Observation.clinicalScore(): a plain sum of every scored field; any missing value leaves it incomplete +export const clinicalScore = (row: Record): number | undefined => { + let total = 0; + for (const f of SCORED_FIELDS) { + const score = scoreOf(row[f.name]); + if (score === undefined) return undefined; + total += score; + } + return total; +}; + +export const displayScore = (score: number | undefined): string => (score === undefined ? '-' : String(score)); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/services/errorText.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/services/errorText.ts new file mode 100644 index 000000000..84a2d597c --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/services/errorText.ts @@ -0,0 +1,3 @@ +// LabKey API failures set exception; JavaScript and network errors set message +export const errorText = (error: any, fallback = 'Unexpected error'): string => + error?.exception ?? error?.message ?? fallback; diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/services/formatDate.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/services/formatDate.ts new file mode 100644 index 000000000..b31c4ff74 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/services/formatDate.ts @@ -0,0 +1,9 @@ +const pad = (n: number) => String(n).padStart(2, '0'); + +export const formatDateTime = (value: Date | string): string => { + if (!value) return ''; + const d = new Date(value); + // A value that won't parse is shown as sent, not as NaN/NaN/NaN + if (isNaN(d.getTime())) return String(value); + return `${pad(d.getMonth() + 1)}/${pad(d.getDate())}/${d.getFullYear()} ${pad(d.getHours())}:${pad(d.getMinutes())}`; +}; diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/styles/biocontainmentObservationReview.scss b/snprc_ehr/src/client/BiocontainmentObservationReview/styles/biocontainmentObservationReview.scss new file mode 100644 index 000000000..cacc1fc6f --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/styles/biocontainmentObservationReview.scss @@ -0,0 +1,122 @@ +@import "../../Shared/styles/components/labkeyGridPanel"; + +// Page wrapper, centred like .snd-lookups-grid +.observation-review { + margin: auto; + width: 95%; +} + +// Line the page title up with the grids, as .lk-body-title does on SND Lookups; same width and centring as .observation-review. +// LabKey renders it as a Bootstrap .col-md-12, which floats above 992px, and auto margins don't centre a float. +// The 16px left padding lines the title text up with the grid's own heading text: the shared +// .panel-default .panel-heading rule insets it 15px, plus the panel's 1px border. +.lk-body-title { + display: block; + float: none; + width: 95%; + margin-left: auto; + margin-right: auto; + padding-left: 16px; + padding-right: 0; + color: #555; +} + +// Grid left, record right on wide screens; stacked below 1200px (same breakpoint as SND Lookups) +@media screen and (min-width: 1200px) { + .observation-review__panels { + display: flex; + align-items: flex-start; + } + .observation-review__grid { + flex: 0 0 600px; + } + .observation-review__detail { + flex: 1 !important; + } +} + +.review-instructions { + color: #555; + margin: 0 0 10px 0; +} + +// Single selection only: no select-all checkbox in the grid header +.observation-review__grid .grid-panel__page-checkbox { + display: none; +} + +// Same treatment as .success-alert +.review-alert { + border-radius: 5px; + margin-bottom: 10px; +} + +// Link to the Recently Approved dataset view +.observation-review__footer-link { + display: inline-block; + margin: 15px 0; +} + +// Same treatment as .lookups-placeholder, without the absolute positioning +.observation-review__placeholder { + color: #555; + margin: 15px; +} + +// Record panel — styled by the shared .panel-default .panel-heading rule so it matches the grid header +.observation-detail { + border-color: #ddd; + border-radius: 5px; + box-shadow: 0 1px 1px rgba(0, 0, 0, .05); + + .panel-body { + padding: 10px 15px 15px; + color: #555; + } + + .table > thead > tr > th { + font-weight: bold; + } + + .form-control { + height: 30px; + padding: 4px 8px; + } + + // A changed value with no reason yet: the server will reject the save, so show it before the round trip + .needs-reason .form-control { + border-color: #c24343; + } + + // The shared .btn rule makes borders transparent; default buttons are white on a white panel + .btn-default { + color: #333; + background-color: #fff; + border-color: #ccc; + + &:hover, + &:focus { + background-color: #e6e6e6; + border-color: #adadad; + } + } + + .btn + .btn { + margin-left: 5px; + } + + // Prior values sit to the left of the current ones; muted so the eye lands on the value under review + .prior-value { + color: #999; + } + + th.prior-value a { + color: inherit; + text-decoration: underline dotted; + cursor: pointer; + } + + .clinical-score { + font-size: 15px; + } +} diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/tests/BiocontainmentObservationReview.test.tsx b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/BiocontainmentObservationReview.test.tsx new file mode 100644 index 000000000..afa95c270 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/BiocontainmentObservationReview.test.tsx @@ -0,0 +1,235 @@ +import React from 'react'; +import { render, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import '@testing-library/jest-dom'; + +import BiocontainmentObservationReview from '../BiocontainmentObservationReview'; +import { approveObservation, fetchObservation } from '../api/observation'; +import { SCORED_FIELDS } from '../constants/fields'; + +jest.mock('../api/observation', () => ({ + approveObservation: jest.fn(), + fetchObservation: jest.fn(), +})); + +// The real grid is a LabKey GridPanel; this stand-in exposes the callbacks the page gives it, and whether Approve is allowed +jest.mock('../components/ReviewGridPanel', () => ({ + ReviewGridPanel: ({ canApprove, onApprove, onFocus }) => ( +
+ + + + + {canApprove ? 'approve enabled' : 'approve disabled'} +
+ ), +})); + +jest.mock('../components/ObservationDetail', () => ({ + __esModule: true, + default: ({ row, onEditingChange }) => ( +
+
detail for {row.Id}
+ + +
+ ), +})); + +const mockApprove = approveObservation as jest.Mock; +const mockFetch = fetchObservation as jest.Mock; + +const MODIFIED = '2026/11/09 10:15:00'; + +// A record with every scored value filled in; Approve is only offered for complete records +const observation = (fields: Record) => ({ + ...Object.fromEntries(SCORED_FIELDS.map(f => [f.name, f.values[0]])), + modified: MODIFIED, + ...fields, +}); + +// The placeholder heading, not the instructions paragraph that starts with the same words +const placeholder = () => screen.queryByRole('heading', { name: /Select an observation to see the full record/ }); + +beforeEach(() => { + jest.clearAllMocks(); + mockFetch.mockImplementation(lsid => + Promise.resolve(observation({ Id: lsid === 'lsid-1' ? '11111' : '22222', lsid })) + ); + mockApprove.mockResolvedValue({}); +}); + +test('shows the placeholder until an observation is selected', () => { + render(); + + expect(placeholder()).toBeInTheDocument(); + expect(mockFetch).not.toHaveBeenCalled(); +}); + +test('opens the selected observation', async () => { + render(); + + userEvent.click(screen.getByText('select lsid-1')); + + expect(await screen.findByText('detail for 11111')).toBeInTheDocument(); + expect(mockFetch).toHaveBeenCalledWith('lsid-1'); +}); + +test('closes the record when it is deselected', async () => { + render(); + userEvent.click(screen.getByText('select lsid-1')); + await screen.findByText('detail for 11111'); + + userEvent.click(screen.getByText('deselect')); + + expect(screen.queryByText('detail for 11111')).not.toBeInTheDocument(); + expect(placeholder()).toBeInTheDocument(); +}); + +test('never shows a slower fetch for a record that is no longer selected', async () => { + let resolveFirst: (row: object) => void; + mockFetch.mockImplementationOnce(() => new Promise(resolve => (resolveFirst = resolve))); + render(); + + userEvent.click(screen.getByText('select lsid-1')); + userEvent.click(screen.getByText('select lsid-2')); + await screen.findByText('detail for 22222'); + + resolveFirst(observation({ Id: '11111', lsid: 'lsid-1' })); + await waitFor(() => expect(screen.queryByText('detail for 11111')).not.toBeInTheDocument()); + expect(screen.getByText('detail for 22222')).toBeInTheDocument(); +}); + +test('approving closes the record and confirms it', async () => { + render(); + userEvent.click(screen.getByText('select lsid-1')); + await screen.findByText('detail for 11111'); + + userEvent.click(screen.getByText('approve lsid-1')); + + expect(await screen.findByText('Observation approved.')).toBeInTheDocument(); + expect(mockApprove).toHaveBeenCalledWith('lsid-1', MODIFIED); + expect(screen.queryByText('detail for 11111')).not.toBeInTheDocument(); + expect(placeholder()).toBeInTheDocument(); +}); + +test('shows the server error and keeps the record open when approval is rejected', async () => { + mockApprove.mockRejectedValue({ exception: 'This observation must be reviewed by someone other than its author' }); + render(); + userEvent.click(screen.getByText('select lsid-1')); + await screen.findByText('detail for 11111'); + + userEvent.click(screen.getByText('approve lsid-1')); + + expect( + await screen.findByText('This observation must be reviewed by someone other than its author') + ).toBeInTheDocument(); + expect(screen.getByText('detail for 11111')).toBeInTheDocument(); +}); + +test('shows the current version after an approval is rejected because the record changed', async () => { + const CHANGED = '2026/11/09 10:20:00'; + mockFetch + .mockResolvedValueOnce(observation({ Id: '11111', lsid: 'lsid-1' })) + .mockResolvedValueOnce(observation({ Id: '11112', lsid: 'lsid-1', modified: CHANGED })); + mockApprove + .mockRejectedValueOnce({ + exception: 'This observation changed after you opened it. Check the current version and approve again.', + }) + .mockResolvedValueOnce({}); + render(); + userEvent.click(screen.getByText('select lsid-1')); + await screen.findByText('detail for 11111'); + + userEvent.click(screen.getByText('approve lsid-1')); + + expect(await screen.findByText('detail for 11112')).toBeInTheDocument(); + expect(screen.getByText(/This observation changed after you opened it/)).toBeInTheDocument(); + expect(mockFetch).toHaveBeenCalledTimes(2); + + // Approving again sends the version now on screen + userEvent.click(screen.getByText('approve lsid-1')); + expect(await screen.findByText('Observation approved.')).toBeInTheDocument(); + expect(mockApprove).toHaveBeenLastCalledWith('lsid-1', CHANGED); +}); + +test('Approve is disabled until the selected record has loaded', async () => { + let resolveFetch: (row: object) => void; + mockFetch.mockImplementationOnce(() => new Promise(resolve => (resolveFetch = resolve))); + render(); + expect(screen.getByText('approve disabled')).toBeInTheDocument(); + + userEvent.click(screen.getByText('select lsid-1')); + expect(screen.getByText('approve disabled')).toBeInTheDocument(); + + resolveFetch(observation({ Id: '11111', lsid: 'lsid-1' })); + expect(await screen.findByText('approve enabled')).toBeInTheDocument(); +}); + +test('Approve is disabled while a correction is being edited', async () => { + render(); + userEvent.click(screen.getByText('select lsid-1')); + await screen.findByText('approve enabled'); + + userEvent.click(screen.getByText('start editing')); + expect(screen.getByText('approve disabled')).toBeInTheDocument(); + + userEvent.click(screen.getByText('stop editing')); + expect(screen.getByText('approve enabled')).toBeInTheDocument(); +}); + +test('ignores an approval for a record that is not on screen', async () => { + render(); + userEvent.click(screen.getByText('select lsid-2')); + await screen.findByText('detail for 22222'); + + userEvent.click(screen.getByText('approve lsid-1')); + + expect(mockApprove).not.toHaveBeenCalled(); +}); + +test('shows a JavaScript or network error message when there is no LabKey exception', async () => { + mockApprove.mockRejectedValue(new Error('Failed to fetch')); + render(); + userEvent.click(screen.getByText('select lsid-1')); + await screen.findByText('detail for 11111'); + + userEvent.click(screen.getByText('approve lsid-1')); + + expect(await screen.findByText('Failed to fetch')).toBeInTheDocument(); +}); + +test('Approve is disabled while a scored value is missing', async () => { + mockFetch.mockResolvedValueOnce(observation({ Id: '11111', lsid: 'lsid-1', Bleeding: null })); + render(); + userEvent.click(screen.getByText('select lsid-1')); + await screen.findByText('detail for 11111'); + + expect(screen.getByText('approve disabled')).toBeInTheDocument(); + userEvent.click(screen.getByText('approve lsid-1')); + expect(mockApprove).not.toHaveBeenCalled(); +}); + +test('Approve is disabled when the record has no version to send', async () => { + mockFetch.mockResolvedValueOnce(observation({ Id: '11111', lsid: 'lsid-1', modified: undefined })); + render(); + userEvent.click(screen.getByText('select lsid-1')); + await screen.findByText('detail for 11111'); + + expect(screen.getByText('approve disabled')).toBeInTheDocument(); +}); + +test('an error from one record is cleared when another record is selected', async () => { + const authorError = 'This observation must be reviewed by someone other than its author'; + mockApprove.mockRejectedValue({ exception: authorError }); + render(); + userEvent.click(screen.getByText('select lsid-1')); + await screen.findByText('detail for 11111'); + userEvent.click(screen.getByText('approve lsid-1')); + await screen.findByText(authorError); + + userEvent.click(screen.getByText('select lsid-2')); + await screen.findByText('detail for 22222'); + + expect(screen.queryByText(authorError)).not.toBeInTheDocument(); +}); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/tests/ObservationDetail.test.tsx b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/ObservationDetail.test.tsx new file mode 100644 index 000000000..42f6ecd29 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/ObservationDetail.test.tsx @@ -0,0 +1,415 @@ +import React from 'react'; +import { render, screen, waitFor, within } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import '@testing-library/jest-dom'; + +import ObservationDetail from '../components/ObservationDetail'; +import { correctObservation, fetchPriorObservation, ObservationRow } from '../api/observation'; +import { SCORED_FIELDS } from '../constants/fields'; + +jest.mock('../api/observation', () => ({ + correctObservation: jest.fn(), + fetchPriorObservation: jest.fn(), + historyUrl: jest.fn(() => '#history'), +})); + +const mockCorrect = correctObservation as jest.Mock; +const mockFetchPrior = fetchPriorObservation as jest.Mock; + +// A complete observation with every scored field at 0 and every carry-over at No +const makeRow = (overrides: Record = {}): ObservationRow => { + const row: ObservationRow = { + lsid: 'lsid-1', + Id: '12345', + Location: 23.03, + date: '2026/09/28 13:45:00', + Comment: 'Quiet morning', + 'createdBy/DisplayName': 'observer', + }; + SCORED_FIELDS.forEach(f => { + row[f.name] = f.name === 'Stool' ? '0' : 0; + if (f.carryOver) row[f.carryOver] = 0; + }); + return { ...row, ...overrides }; +}; + +// The table row for one parameter, so its value, carry-over and reason controls can be found by label +const parameterRow = (label: string) => within(screen.getByText(label).closest('tr')); + +const renderDetail = async (row: ObservationRow = makeRow(), onSaved = jest.fn(), onEditingChange = jest.fn()) => { + render(); + // Let the prior-observation fetch settle before asserting + await waitFor(() => expect(mockFetchPrior).toHaveBeenCalled()); + return onSaved; +}; + +const saveButton = () => screen.getByRole('button', { name: 'Save correction' }); + +beforeEach(() => { + jest.clearAllMocks(); + mockFetchPrior.mockResolvedValue(undefined); + mockCorrect.mockResolvedValue({}); +}); + +describe('ObservationDetail, read only', () => { + test('shows the animal, location, time, author and comment', async () => { + await renderDetail(); + + expect(screen.getByText('12345 · Location 23.03 · 09/28/2026 13:45')).toBeInTheDocument(); + expect(screen.getByText('Recorded by observer')).toBeInTheDocument(); + expect(screen.getByText('Comment: Quiet morning')).toBeInTheDocument(); + }); + + test('lists all 13 parameters with the calculated clinical score', async () => { + await renderDetail(makeRow({ Respiration: 8, Stool: '2R' })); + + SCORED_FIELDS.forEach(f => expect(screen.getByText(f.label)).toBeInTheDocument()); + expect(screen.getByText('Clinical Score:')).toHaveTextContent('Clinical Score: 10'); + }); + + test('shows carry-overs as Yes or No', async () => { + await renderDetail(makeRow({ PetechiaCO: 1 })); + + expect(parameterRow('Petechia').getByText('Yes')).toBeInTheDocument(); + expect(parameterRow('Weight Loss').getByText('No')).toBeInTheDocument(); + }); + + test('hides the Prior column when there is no earlier observation', async () => { + await renderDetail(); + + expect(screen.queryByRole('link', { name: 'Prior' })).not.toBeInTheDocument(); + }); + + test('shows the prior values and prior score, linked to the full history', async () => { + mockFetchPrior.mockResolvedValue(makeRow({ lsid: 'prior', Bleeding: 2 })); + await renderDetail(); + + const link = await screen.findByRole('link', { name: 'Prior' }); + expect(link).toHaveAttribute('href', '#history'); + expect(parameterRow('Bleeding').getByText('2')).toBeInTheDocument(); + expect(screen.getByText('(prior 2)', { exact: false })).toBeInTheDocument(); + }); + + test('shows an error if the prior observation cannot be loaded', async () => { + mockFetchPrior.mockRejectedValue({ exception: 'Query failed' }); + await renderDetail(); + + expect(await screen.findByText('Query failed')).toBeInTheDocument(); + }); +}); + +describe('ObservationDetail, corrections', () => { + test('Save stays disabled until a value actually changes', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + expect(saveButton()).toBeDisabled(); + }); + + test('a changed value needs a reason before it can be saved', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const bleeding = parameterRow('Bleeding'); + userEvent.selectOptions(bleeding.getByRole('combobox'), '2'); + expect(saveButton()).toBeDisabled(); + expect(screen.getByText('Bleeding').closest('tr').querySelector('.needs-reason')).not.toBeNull(); + + userEvent.type(bleeding.getByRole('textbox'), 'Entered on the wrong animal'); + expect(saveButton()).toBeEnabled(); + }); + + test('a reason of only spaces does not count', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const bleeding = parameterRow('Bleeding'); + userEvent.selectOptions(bleeding.getByRole('combobox'), '1'); + userEvent.type(bleeding.getByRole('textbox'), ' '); + + expect(saveButton()).toBeDisabled(); + }); + + test('changing a value back to the original is not a change', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const select = parameterRow('Bleeding').getByRole('combobox'); + userEvent.selectOptions(select, '2'); + userEvent.selectOptions(select, '0'); + + expect(saveButton()).toBeDisabled(); + }); + + test('changing only a carry-over also needs the parameter reason', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const petechia = parameterRow('Petechia'); + const [, carryOver] = petechia.getAllByRole('combobox'); + userEvent.selectOptions(carryOver, '1'); + expect(saveButton()).toBeDisabled(); + + userEvent.type(petechia.getByRole('textbox'), 'Carried from AM'); + expect(saveButton()).toBeEnabled(); + }); + + test('the clinical score follows unsaved edits', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + userEvent.selectOptions(parameterRow('Responsiveness').getByRole('combobox'), '15'); + + expect(screen.getByText('Clinical Score:')).toHaveTextContent('Clinical Score: 15'); + }); + + test('saves only the changed parameters, with their reasons, then reports back', async () => { + const onSaved = await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const bleeding = parameterRow('Bleeding'); + userEvent.selectOptions(bleeding.getByRole('combobox'), '2'); + userEvent.type(bleeding.getByRole('textbox'), 'Entered on the wrong animal'); + + const petechia = parameterRow('Petechia'); + userEvent.selectOptions(petechia.getAllByRole('combobox')[1], '1'); + userEvent.type(petechia.getByRole('textbox'), 'Carried from AM'); + + // Touched but unchanged: must not be sent + userEvent.type(parameterRow('Stool').getByRole('textbox'), 'no change'); + + userEvent.click(saveButton()); + + await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1)); + expect(mockCorrect).toHaveBeenCalledWith( + 'lsid-1', + [ + { carryOver: undefined, field: 'Bleeding', reason: 'Entered on the wrong animal', value: '2' }, + { carryOver: 1, field: 'Petechia', reason: 'Carried from AM', value: 0 }, + ], + // Comment untouched, so it is not sent + undefined + ); + expect(screen.getByRole('button', { name: 'Edit Values' })).toBeInTheDocument(); + }); + + test('shows the server error and stays in edit mode when the save is rejected', async () => { + mockCorrect.mockRejectedValue({ exception: 'A reason is required for each changed value' }); + const onSaved = await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const bleeding = parameterRow('Bleeding'); + userEvent.selectOptions(bleeding.getByRole('combobox'), '1'); + userEvent.type(bleeding.getByRole('textbox'), 'Typo'); + userEvent.click(saveButton()); + + expect(await screen.findByText('A reason is required for each changed value')).toBeInTheDocument(); + expect(onSaved).not.toHaveBeenCalled(); + expect(saveButton()).toBeInTheDocument(); + }); + + test('Cancel discards the edits', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + userEvent.selectOptions(parameterRow('Bleeding').getByRole('combobox'), '2'); + + userEvent.click(screen.getByRole('button', { name: 'Cancel' })); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + expect(parameterRow('Bleeding').getByRole('combobox')).toHaveValue('0'); + expect(screen.getByText('Clinical Score:')).toHaveTextContent('Clinical Score: 0'); + expect(mockCorrect).not.toHaveBeenCalled(); + }); + + test('the reason must differ from the one already stored', async () => { + await renderDetail(makeRow({ BleedingComments: 'Entered on the wrong animal' })); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const bleeding = parameterRow('Bleeding'); + userEvent.selectOptions(bleeding.getByRole('combobox'), '2'); + userEvent.type(bleeding.getByRole('textbox'), 'Entered on the wrong animal'); + expect(saveButton()).toBeDisabled(); + + userEvent.type(bleeding.getByRole('textbox'), ' again'); + expect(saveButton()).toBeEnabled(); + }); + + test('Cancel clears the error from a rejected save', async () => { + mockCorrect.mockRejectedValue({ exception: 'Save rejected' }); + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const bleeding = parameterRow('Bleeding'); + userEvent.selectOptions(bleeding.getByRole('combobox'), '1'); + userEvent.type(bleeding.getByRole('textbox'), 'Typo'); + userEvent.click(saveButton()); + await screen.findByText('Save rejected'); + + userEvent.click(screen.getByRole('button', { name: 'Cancel' })); + + expect(screen.queryByText('Save rejected')).not.toBeInTheDocument(); + }); + + test('shows a JavaScript or network error message when there is no LabKey exception', async () => { + mockCorrect.mockRejectedValue(new Error('Failed to fetch')); + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const bleeding = parameterRow('Bleeding'); + userEvent.selectOptions(bleeding.getByRole('combobox'), '1'); + userEvent.type(bleeding.getByRole('textbox'), 'Typo'); + userEvent.click(saveButton()); + + expect(await screen.findByText('Failed to fetch')).toBeInTheDocument(); + }); + + test('tells the page when editing starts and stops, so it can disable Approve', async () => { + const onEditingChange = jest.fn(); + await renderDetail(makeRow(), jest.fn(), onEditingChange); + expect(onEditingChange).toHaveBeenLastCalledWith(false); + + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + expect(onEditingChange).toHaveBeenLastCalledWith(true); + + userEvent.click(screen.getByRole('button', { name: 'Cancel' })); + expect(onEditingChange).toHaveBeenLastCalledWith(false); + }); +}); + +describe('ObservationDetail, missing values', () => { + test('marks a missing value instead of leaving it blank', async () => { + await renderDetail(makeRow({ Bleeding: null })); + + expect(parameterRow('Bleeding').getByText('Missing')).toBeInTheDocument(); + }); + + test('a missing value shows as unselected, not as the first choice, and can be filled in with a reason', async () => { + const onSaved = await renderDetail(makeRow({ Bleeding: null })); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const bleeding = parameterRow('Bleeding'); + const select = bleeding.getByRole('combobox') as HTMLSelectElement; + expect(select.value).toBe(''); + expect(bleeding.getByRole('option', { name: 'Select a value' })).toBeDisabled(); + expect(saveButton()).toBeDisabled(); + + userEvent.selectOptions(select, '1'); + userEvent.type(bleeding.getByRole('textbox'), 'Missing from the tablet'); + userEvent.click(saveButton()); + + await waitFor(() => expect(onSaved).toHaveBeenCalled()); + expect(mockCorrect).toHaveBeenCalledWith( + 'lsid-1', + [{ carryOver: undefined, field: 'Bleeding', reason: 'Missing from the tablet', value: '1' }], + undefined + ); + }); + + test('Save stays disabled while another value is still missing', async () => { + await renderDetail(makeRow({ Bleeding: null })); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const stool = parameterRow('Stool'); + userEvent.selectOptions(stool.getByRole('combobox'), '1'); + userEvent.type(stool.getByRole('textbox'), 'Entered on the wrong animal'); + expect(saveButton()).toBeDisabled(); + expect(screen.getByText(/Fill in every missing value before saving: Bleeding/)).toBeInTheDocument(); + + const bleeding = parameterRow('Bleeding'); + userEvent.selectOptions(bleeding.getByRole('combobox'), '0'); + userEvent.type(bleeding.getByRole('textbox'), 'Missing from the tablet'); + expect(saveButton()).toBeEnabled(); + expect(screen.queryByText(/Fill in every missing value/)).not.toBeInTheDocument(); + }); + + test('a complete record has no blank choice', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + expect(parameterRow('Bleeding').queryByRole('option', { name: 'Select a value' })).not.toBeInTheDocument(); + }); +}); + +describe('ObservationDetail, comment', () => { + const commentBox = () => screen.getByLabelText('Comment'); + + test('is read only until editing starts', async () => { + await renderDetail(); + + expect(screen.getByText('Comment: Quiet morning')).toBeInTheDocument(); + expect(screen.queryByLabelText('Comment')).not.toBeInTheDocument(); + }); + + test('is editable, limited to the 80 characters CAMP stores', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + expect(commentBox()).toHaveValue('Quiet morning'); + expect(commentBox()).toHaveAttribute('maxLength', '80'); + }); + + test('a comment change can be saved on its own, with no reason', async () => { + const onSaved = await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + userEvent.clear(commentBox()); + userEvent.type(commentBox(), 'Lethargic after feeding'); + expect(saveButton()).toBeEnabled(); + + userEvent.click(saveButton()); + + await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1)); + expect(mockCorrect).toHaveBeenCalledWith('lsid-1', [], 'Lethargic after feeding'); + }); + + test('clearing the comment sends an empty comment', async () => { + const onSaved = await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + userEvent.clear(commentBox()); + userEvent.click(saveButton()); + + await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1)); + expect(mockCorrect).toHaveBeenCalledWith('lsid-1', [], ''); + }); + + test('retyping the same comment, or only adding spaces, is not a change', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + userEvent.clear(commentBox()); + userEvent.type(commentBox(), 'Quiet morning '); + + expect(saveButton()).toBeDisabled(); + }); + + test('a comment change is saved together with value corrections', async () => { + const onSaved = await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + const bleeding = parameterRow('Bleeding'); + userEvent.selectOptions(bleeding.getByRole('combobox'), '1'); + userEvent.type(bleeding.getByRole('textbox'), 'Typo'); + userEvent.type(commentBox(), ', small bleed noted'); + userEvent.click(saveButton()); + + await waitFor(() => expect(onSaved).toHaveBeenCalledTimes(1)); + expect(mockCorrect).toHaveBeenCalledWith( + 'lsid-1', + [{ carryOver: undefined, field: 'Bleeding', reason: 'Typo', value: '1' }], + 'Quiet morning, small bleed noted' + ); + }); + + test('Cancel discards a comment edit', async () => { + await renderDetail(); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + userEvent.clear(commentBox()); + userEvent.type(commentBox(), 'Something else'); + + userEvent.click(screen.getByRole('button', { name: 'Cancel' })); + userEvent.click(screen.getByRole('button', { name: 'Edit Values' })); + + expect(commentBox()).toHaveValue('Quiet morning'); + }); +}); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/tests/clinicalScore.test.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/clinicalScore.test.ts new file mode 100644 index 000000000..a742545ed --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/clinicalScore.test.ts @@ -0,0 +1,67 @@ +import { clinicalScore, displayScore, scoreOf } from '../services/clinicalScore'; +import { SCORED_FIELDS } from '../constants/fields'; + +// Every scored field at 0, as LabKey returns them (Stool is the one varchar) +const zeroRow = (): Record => + SCORED_FIELDS.reduce((row, f) => ({ ...row, [f.name]: f.name === 'Stool' ? '0' : 0 }), {}); + +describe('scoreOf', () => { + test('reads numeric values', () => { + expect(scoreOf(0)).toBe(0); + expect(scoreOf(15)).toBe(15); + expect(scoreOf('8')).toBe(8); + }); + + test('scores Stool 2D and 2R as 2, like the tablet and CAMP', () => { + expect(scoreOf('2D')).toBe(2); + expect(scoreOf('2R')).toBe(2); + }); + + test('treats empty and non-numeric values as missing', () => { + expect(scoreOf(null)).toBeUndefined(); + expect(scoreOf(undefined)).toBeUndefined(); + expect(scoreOf('')).toBeUndefined(); + expect(scoreOf('abc')).toBeUndefined(); + }); +}); + +describe('clinicalScore', () => { + test('is 0 when every field is 0', () => { + expect(clinicalScore(zeroRow())).toBe(0); + }); + + test('sums every scored field, including Stool', () => { + const row = { ...zeroRow(), Responsiveness: 8, Petechia: 3, Stool: '2R', Bleeding: 1 }; + expect(clinicalScore(row)).toBe(14); + }); + + test('reaches the euthanasia threshold of 15 on Respiration alone', () => { + expect(clinicalScore({ ...zeroRow(), Respiration: 15 })).toBe(15); + }); + + test('is incomplete when any scored field is missing', () => { + const row = zeroRow(); + delete row.Dehydration; + expect(clinicalScore(row)).toBeUndefined(); + }); + + test('ignores carry-over and comment columns', () => { + expect(clinicalScore({ ...zeroRow(), WeightLossCO: 1, WeightLossComments: 'typo' })).toBe(0); + }); + + test('maximum possible score matches the TXB 904-1 scales', () => { + const maxRow = SCORED_FIELDS.reduce( + (row, f) => ({ ...row, [f.name]: f.values[f.values.length - 1] }), + {} as Record + ); + expect(clinicalScore(maxRow)).toBe(49); + }); +}); + +describe('displayScore', () => { + test('shows a dash for an incomplete score', () => { + expect(displayScore(undefined)).toBe('-'); + expect(displayScore(0)).toBe('0'); + expect(displayScore(17)).toBe('17'); + }); +}); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/tests/fields.test.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/fields.test.ts new file mode 100644 index 000000000..cc372c4e2 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/fields.test.ts @@ -0,0 +1,71 @@ +import { carryOverOf, COMPLETED, missingFields, REVIEW_REQUIRED, SCORED_FIELDS } from '../constants/fields'; + +describe('SCORED_FIELDS', () => { + test('has the 13 parameters on TXB 904-1, in form order', () => { + expect(SCORED_FIELDS.map(f => f.name)).toEqual([ + 'WeightLoss', + 'TemperatureChange', + 'Responsiveness', + 'HairCoat', + 'Respiration', + 'Petechia', + 'Bleeding', + 'NasalDischarge', + 'FeedEaten', + 'FoodEnrichment', + 'Stool', + 'FluidIntake', + 'Dehydration', + ]); + }); + + // Guards against the page offering a value CAMP's CK_* constraints reject, which would fail the write-back + test('allowed values match the CHECK constraints on dbo.BiocontainmentObservation', () => { + const values = Object.fromEntries(SCORED_FIELDS.map(f => [f.name, f.values])); + expect(values).toEqual({ + WeightLoss: [0, 1, 2], + TemperatureChange: [0, 1, 2, 3], + Responsiveness: [0, 1, 2, 8, 15], + HairCoat: [0, 1], + Respiration: [0, 8, 15], + Petechia: [0, 1, 2, 3], + Bleeding: [0, 1, 2], + NasalDischarge: [0, 1], + FeedEaten: [0, 1], + FoodEnrichment: [0, 1], + Stool: ['0', '1', '2D', '2R'], + FluidIntake: [0, 1, 2], + Dehydration: [0, 1], + }); + }); +}); + +describe('carryOverOf', () => { + test('returns the carry-over column for the six fields that have one', () => { + expect(carryOverOf('WeightLoss')).toBe('WeightLossCO'); + expect(carryOverOf('TemperatureChange')).toBe('TemperatureChangeCO'); + expect(carryOverOf('Petechia')).toBe('PetechiaCO'); + expect(carryOverOf('FeedEaten')).toBe('FeedEatenCO'); + expect(carryOverOf('FoodEnrichment')).toBe('FoodEnrichmentCO'); + expect(carryOverOf('Dehydration')).toBe('DehydrationCO'); + expect(SCORED_FIELDS.filter(f => f.carryOver)).toHaveLength(6); + }); + + test('returns undefined for fields without one and for unknown fields', () => { + expect(carryOverOf('Responsiveness')).toBeUndefined(); + expect(carryOverOf('Comment')).toBeUndefined(); + }); +}); + +test('QC state labels match the study QC states', () => { + expect(REVIEW_REQUIRED).toBe('Review Required'); + expect(COMPLETED).toBe('Completed'); +}); + +describe('missingFields', () => { + test('lists the parameters with no value; 0 is a value', () => { + const row = Object.fromEntries(SCORED_FIELDS.map(f => [f.name, 0])); + expect(missingFields(row)).toEqual([]); + expect(missingFields({ ...row, Bleeding: null, Stool: '' }).map(f => f.name)).toEqual(['Bleeding', 'Stool']); + }); +}); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/tests/formatDate.test.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/formatDate.test.ts new file mode 100644 index 000000000..6798ddc61 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/formatDate.test.ts @@ -0,0 +1,21 @@ +import { formatDateTime } from '../services/formatDate'; + +describe('formatDateTime', () => { + test('formats as MM/dd/yyyy HH:mm in 24-hour time', () => { + expect(formatDateTime(new Date(2026, 8, 28, 13, 5))).toBe('09/28/2026 13:05'); + expect(formatDateTime(new Date(2026, 0, 2, 7, 0))).toBe('01/02/2026 07:00'); + }); + + test('accepts the date string LabKey returns', () => { + expect(formatDateTime('2026/09/28 13:45:00')).toBe('09/28/2026 13:45'); + }); + + test('returns an empty string for a missing date', () => { + expect(formatDateTime('')).toBe(''); + expect(formatDateTime(undefined)).toBe(''); + }); + + test('returns the value unchanged when it is not a date', () => { + expect(formatDateTime('not a date')).toBe('not a date'); + }); +}); diff --git a/snprc_ehr/src/client/BiocontainmentObservationReview/tests/observation.test.ts b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/observation.test.ts new file mode 100644 index 000000000..1047a04d6 --- /dev/null +++ b/snprc_ehr/src/client/BiocontainmentObservationReview/tests/observation.test.ts @@ -0,0 +1,182 @@ +import { Filter, Query } from '@labkey/api'; +import { + approveObservation, + correctObservation, + fetchObservation, + fetchPriorObservation, + historyUrl, +} from '../api/observation'; + +jest.mock('@labkey/api', () => { + const actual = jest.requireActual('@labkey/api'); + return { + ...actual, + ActionURL: { + buildURL: jest.fn((controller, action, container, params) => ({ action, controller, params })), + }, + Query: { selectRows: jest.fn(), updateRows: jest.fn() }, + }; +}); + +const selectRows = Query.selectRows as jest.Mock; +const updateRows = Query.updateRows as jest.Mock; + +// Answer the next LabKey call the way the server would +const succeedWith = (mock: jest.Mock, data: unknown) => mock.mockImplementation(config => config.success(data)); +const failWith = (mock: jest.Mock, error: unknown) => mock.mockImplementation(config => config.failure(error)); + +const filterSummary = (filters: Filter.IFilter[]) => + filters.map(f => [f.getColumnName(), f.getFilterType().getURLSuffix(), f.getValue()]); + +beforeEach(() => { + jest.clearAllMocks(); +}); + +describe('approveObservation', () => { + test('sends the lsid, the Completed QC state and the version reviewed; the trigger stamps the reviewer', async () => { + succeedWith(updateRows, { rows: [] }); + + await approveObservation('lsid-1', '2026/11/09 10:15:00'); + + const config = updateRows.mock.calls[0][0]; + expect(config.schemaName).toBe('study'); + expect(config.queryName).toBe('BiocontainmentObservations'); + expect(config.rows).toEqual([ + { lsid: 'lsid-1', QCStateLabel: 'Completed', viewedModified: '2026/11/09 10:15:00' }, + ]); + }); + + test('rejects with the server error, e.g. the author trying to approve', async () => { + const error = { exception: 'This observation must be reviewed by someone other than its author' }; + failWith(updateRows, error); + + await expect(approveObservation('lsid-1', '2026/11/09 10:15:00')).rejects.toBe(error); + }); + + test('refuses without the version reviewed, rather than letting the server report a misleading change', async () => { + await expect(approveObservation('lsid-1', undefined)).rejects.toEqual({ + exception: expect.stringContaining('version is unknown'), + }); + expect(updateRows).not.toHaveBeenCalled(); + }); +}); + +describe('correctObservation', () => { + test('sends each changed value with its reason in the matching Comments column', async () => { + succeedWith(updateRows, { rows: [] }); + + await correctObservation('lsid-1', [ + { field: 'Responsiveness', reason: 'Entered on the wrong row', value: '8' }, + { field: 'Stool', reason: 'Was 2R', value: '2D' }, + ]); + + expect(updateRows.mock.calls[0][0].rows).toEqual([ + { + lsid: 'lsid-1', + Responsiveness: '8', + ResponsivenessComments: 'Entered on the wrong row', + Stool: '2D', + StoolComments: 'Was 2R', + }, + ]); + }); + + test('sends the carry-over with its parameter, sharing the reason', async () => { + succeedWith(updateRows, { rows: [] }); + + await correctObservation('lsid-1', [{ carryOver: 1, field: 'Petechia', reason: 'Carried from AM', value: 2 }]); + + expect(updateRows.mock.calls[0][0].rows[0]).toEqual({ + lsid: 'lsid-1', + Petechia: 2, + PetechiaCO: 1, + PetechiaComments: 'Carried from AM', + }); + }); + + test('ignores a carry-over on a field that does not have one', async () => { + succeedWith(updateRows, { rows: [] }); + + await correctObservation('lsid-1', [{ carryOver: 1, field: 'Bleeding', reason: 'Typo', value: 1 }]); + + expect(updateRows.mock.calls[0][0].rows[0]).toEqual({ lsid: 'lsid-1', Bleeding: 1, BleedingComments: 'Typo' }); + }); + + test('sends the comment only when one is passed, and an empty comment as null', async () => { + succeedWith(updateRows, { rows: [] }); + + await correctObservation('lsid-1', [{ field: 'Bleeding', reason: 'Typo', value: 1 }]); + expect(updateRows.mock.calls[0][0].rows[0]).not.toHaveProperty('Comment'); + + await correctObservation('lsid-1', [], 'Lethargic after feeding'); + expect(updateRows.mock.calls[1][0].rows[0]).toEqual({ Comment: 'Lethargic after feeding', lsid: 'lsid-1' }); + + await correctObservation('lsid-1', [], ''); + expect(updateRows.mock.calls[2][0].rows[0]).toEqual({ Comment: null, lsid: 'lsid-1' }); + }); + + test('rejects with the server error, e.g. a missing reason', async () => { + const error = { exception: 'A reason is required for each changed value' }; + failWith(updateRows, error); + + await expect(correctObservation('lsid-1', [{ field: 'Bleeding', reason: '', value: 1 }])).rejects.toBe(error); + }); +}); + +describe('fetchObservation', () => { + test('selects the one row by lsid, with every scored, reason and carry-over column', async () => { + const row = { lsid: 'lsid-1', Id: '12345' }; + succeedWith(selectRows, { rows: [row] }); + + await expect(fetchObservation('lsid-1')).resolves.toBe(row); + + const config = selectRows.mock.calls[0][0]; + expect(filterSummary(config.filterArray)).toEqual([['lsid', 'eq', 'lsid-1']]); + expect(config.columns).toEqual( + expect.arrayContaining(['lsid', 'QCState/Label', 'Petechia', 'PetechiaComments', 'PetechiaCO', 'Stool']) + ); + expect(config.columns).not.toContain('StoolCO'); + }); +}); + +describe('fetchPriorObservation', () => { + const row = { date: '2026/09/28 13:45:00', Id: '12345', Location: 23.03 }; + + test('asks for the latest earlier observation of the same animal at the same location', async () => { + succeedWith(selectRows, { rows: [{ lsid: 'prior' }] }); + + await expect(fetchPriorObservation(row)).resolves.toEqual({ lsid: 'prior' }); + + const config = selectRows.mock.calls[0][0]; + // LESS_THAN, not DATE_LESS_THAN: an animal can have two observations on the same day + expect(filterSummary(config.filterArray)).toEqual([ + ['Id', 'eq', '12345'], + ['Location', 'eq', 23.03], + ['date', 'lt', '2026/09/28 13:45:00'], + ]); + expect(config.sort).toBe('-date'); + expect(config.maxRows).toBe(1); + }); + + test('resolves undefined for the first observation', async () => { + succeedWith(selectRows, { rows: [] }); + + await expect(fetchPriorObservation(row)).resolves.toBeUndefined(); + }); +}); + +describe('historyUrl', () => { + test('opens the dataset filtered to the animal and location, newest first', () => { + expect(historyUrl({ Id: '12345', Location: 23.03 })).toEqual({ + action: 'executeQuery', + controller: 'query', + params: { + 'query.Id~eq': '12345', + 'query.Location~eq': 23.03, + 'query.queryName': 'BiocontainmentObservations', + 'query.sort': '-date', + schemaName: 'study', + }, + }); + }); +}); diff --git a/snprc_ehr/src/client/Shared/styles/components/_labkeyGridPanel.scss b/snprc_ehr/src/client/Shared/styles/components/_labkeyGridPanel.scss new file mode 100644 index 000000000..4a897e5a3 --- /dev/null +++ b/snprc_ehr/src/client/Shared/styles/components/_labkeyGridPanel.scss @@ -0,0 +1,189 @@ +// LabKey GridPanel, modal, button, form and dropdown restyling shared by the SND Lookups and +// Biocontainment Observation Review pages. Moved verbatim from sndLookupsManagement.scss. + +// Make header sticky +.lk-header-ct { + position: sticky; + top: 0; + z-index: 1000; +} + +// GridPanel styling customization +.grid-panel__grid .table-responsive { + overflow-y: scroll; + width: 100%; + z-index: 1; + top: 0; + left: 0; + transition: .5s ease; + align-items: center; + border-radius: 4px; + height: 54vh !important; +} +.grid-panel__grid .table-responsive thead { + position: sticky; + top: -1px; + z-index: 2; +} +.grid-panel__grid .table-responsive thead th { + background-color: #FFFFFF; + /* fix for weird FF behavior, described in https://stackoverflow.com/questions/7517127/ */ + background-clip: padding-box; + font-weight: bold; +} +.grid-panel__grid .table-responsive thead th#__selection__, +.grid-panel__grid .table-responsive thead th .grid-header-cell__body { + padding: 5px; +} + +.dropdown-menu.grid-header-cell__dropdown-menu { + display: block; + position: fixed; +} + +.grid-panel { + border-color: #ddd; + border-radius: 5px; + -webkit-box-shadow: 0 1px 1px rgba(0,0,0,.05); + box-shadow: 0 1px 1px rgba(0,0,0,.05); +} +.grid-panel__body { + font-family: "Roboto","Helvetica Neue",Helvetica,Arial,sans-serif; +} +.panel-default .panel-heading { + background-color: #fff; + font-family: "Roboto","Helvetica Neue",Helvetica,Arial,sans-serif; + font-size: 18px; + color: #555; + line-height: 1.428571429; + border-bottom: 1px solid #ddd; + margin: 15px 15px 0 15px; + padding: 0px 0px 10px; +} +.ws-pre-wrap { + color: #555; + cursor: default; +} +.grid-panel__row-checkbox { + cursor: pointer; +} +.grid-header-cell { + touch-action: manipulation; + cursor: pointer; +} + +// Customize button bar on grid +.button-bar__section { + display: flex; + float: left; + margin-bottom: 5px; +} +.input-group-addon { + border-radius: 5px; + padding: 6px 12px; + font-size: 14px; + font-weight: 400; + line-height: 1; + color: #555; + text-align: center; + background-color: #eee; + border: 1px solid #ccc; +} +.input-group-addon, .input-group-btn, .input-group .form-control { + display: table-cell; +} +.input-group-addon, .input-group-btn { + white-space: nowrap; + vertical-align: middle; +} +.grid-panel__input-group { + margin-left: 5px; +} + +.input-group-btn { + border-radius: 5px; + color: #555; + background-color: #fff; + border: 1px solid #ccc; +} + +.grid-panel__filter-status { + display: block; + white-space: pre-wrap; + padding-top: 40px; +} + +// Labkey modal customization +.modal-content { + font-family: "Roboto","Helvetica Neue",Helvetica,Arial,sans-serif; + position: relative; + left: 7%; + width: 85%; + border-radius: 5px; + transform: translate(0, 10%) +} + +.modal-header { + font-family: "Roboto","Helvetica Neue",Helvetica,Arial,sans-serif; + border-bottom: 1px solid #ddd; + border-top-left-radius: 5px; + border-top-right-radius: 5px; +} + +// Labkey modal fix for Filters +.modal-lg { + position: relative; +} +.labkey-wizard-pills { + overflow-y: scroll; + height: 40vh; +} +.form-check { + display: inline-flex; +} + +// Styling for all buttons +.btn { + touch-action: manipulation; + cursor: pointer; + border-radius: 5px; + display: inline-block; + margin-bottom: 0; + font-weight: normal; + text-align: center; + white-space: nowrap; + vertical-align: middle; + background-image: none; + border: 1px solid rgba(0,0,0,0); + padding: 6px 12px; + font-size: 12px; + line-height: 1.428571429; +} + +// Styling for all forms +.form-control { + border-radius: 5px; + display: block; + width: 100%; + height: 34px; + padding: 6px 12px; + font-size: 14px; + line-height: 1.428571429; + color: #555; + background-color: #fff; + background-image: none; + border: 1px solid #ccc; + -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075); + box-shadow: inset 0 1px 1px rgba(0,0,0,.075); + -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; + -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; + transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; +} + +// Styling for all dropdowns +.dropdown-menu { + border-radius: 5px; +} +.select-dropdown { + width: 60%; +} diff --git a/snprc_ehr/src/client/SndLookupsManagement/styles/sndLookupsManagement.scss b/snprc_ehr/src/client/SndLookupsManagement/styles/sndLookupsManagement.scss index b66f7b433..3b3b248d2 100644 --- a/snprc_ehr/src/client/SndLookupsManagement/styles/sndLookupsManagement.scss +++ b/snprc_ehr/src/client/SndLookupsManagement/styles/sndLookupsManagement.scss @@ -1,3 +1,5 @@ +@import "../../Shared/styles/components/labkeyGridPanel"; + // When screen is small @media screen and (max-width: 992px) { .snd-lookups-grid { @@ -35,13 +37,6 @@ } } -// Make header sticky -.lk-header-ct { - position: sticky; - top: 0; - z-index: 1000; -} - // Move title to center .lk-body-title { width: 60%; @@ -110,186 +105,6 @@ margin-bottom: -10px; } -// GridPanel styling customization -.grid-panel__grid .table-responsive { - overflow-y: scroll; - width: 100%; - z-index: 1; - top: 0; - left: 0; - transition: .5s ease; - align-items: center; - border-radius: 4px; - height: 54vh !important; -} -.grid-panel__grid .table-responsive thead { - position: sticky; - top: -1px; - z-index: 2; -} -.grid-panel__grid .table-responsive thead th { - background-color: #FFFFFF; - /* fix for weird FF behavior, described in https://stackoverflow.com/questions/7517127/ */ - background-clip: padding-box; - font-weight: bold; -} -.grid-panel__grid .table-responsive thead th#__selection__, -.grid-panel__grid .table-responsive thead th .grid-header-cell__body { - padding: 5px; -} - -.dropdown-menu.grid-header-cell__dropdown-menu { - display: block; - position: fixed; -} - -.grid-panel { - border-color: #ddd; - border-radius: 5px; - -webkit-box-shadow: 0 1px 1px rgba(0,0,0,.05); - box-shadow: 0 1px 1px rgba(0,0,0,.05); -} -.grid-panel__body { - font-family: "Roboto","Helvetica Neue",Helvetica,Arial,sans-serif; -} -.panel-default .panel-heading { - background-color: #fff; - font-family: "Roboto","Helvetica Neue",Helvetica,Arial,sans-serif; - font-size: 18px; - color: #555; - line-height: 1.428571429; - border-bottom: 1px solid #ddd; - margin: 15px 15px 0 15px; - padding: 0px 0px 10px; -} -.ws-pre-wrap { - color: #555; - cursor: default; -} -.grid-panel__row-checkbox { - cursor: pointer; -} -.grid-header-cell { - touch-action: manipulation; - cursor: pointer; -} - -// Customize button bar on grid -.button-bar__section { - display: flex; - float: left; - margin-bottom: 5px; -} -.input-group-addon { - border-radius: 5px; - padding: 6px 12px; - font-size: 14px; - font-weight: 400; - line-height: 1; - color: #555; - text-align: center; - background-color: #eee; - border: 1px solid #ccc; -} -.input-group-addon, .input-group-btn, .input-group .form-control { - display: table-cell; -} -.input-group-addon, .input-group-btn { - white-space: nowrap; - vertical-align: middle; -} -.grid-panel__input-group { - margin-left: 5px; -} - -.input-group-btn { - border-radius: 5px; - color: #555; - background-color: #fff; - border: 1px solid #ccc; -} - -.grid-panel__filter-status { - display: block; - white-space: pre-wrap; - padding-top: 40px; -} - -// Labkey modal customization -.modal-content { - font-family: "Roboto","Helvetica Neue",Helvetica,Arial,sans-serif; - position: relative; - left: 7%; - width: 85%; - border-radius: 5px; - transform: translate(0, 10%) -} - -.modal-header { - font-family: "Roboto","Helvetica Neue",Helvetica,Arial,sans-serif; - border-bottom: 1px solid #ddd; - border-top-left-radius: 5px; - border-top-right-radius: 5px; -} - -// Labkey modal fix for Filters -.modal-lg { - position: relative; -} -.labkey-wizard-pills { - overflow-y: scroll; - height: 40vh; -} -.form-check { - display: inline-flex; -} - -// Styling for all buttons -.btn { - touch-action: manipulation; - cursor: pointer; - border-radius: 5px; - display: inline-block; - margin-bottom: 0; - font-weight: normal; - text-align: center; - white-space: nowrap; - vertical-align: middle; - background-image: none; - border: 1px solid rgba(0,0,0,0); - padding: 6px 12px; - font-size: 12px; - line-height: 1.428571429; -} - -// Styling for all forms -.form-control { - border-radius: 5px; - display: block; - width: 100%; - height: 34px; - padding: 6px 12px; - font-size: 14px; - line-height: 1.428571429; - color: #555; - background-color: #fff; - background-image: none; - border: 1px solid #ccc; - -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075); - box-shadow: inset 0 1px 1px rgba(0,0,0,.075); - -webkit-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; - -o-transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; - transition: border-color ease-in-out .15s,box-shadow ease-in-out .15s; -} - -// Styling for all dropdowns -.dropdown-menu { - border-radius: 5px; -} -.select-dropdown { - width: 60%; -} - // Removing labkey objects don't need to be displayed .selection-status__count, .selection-status__select-all, .grid-panel__loading, .selection-status__clear-all, .view-menu, .alert-info, .button-left-spacing, .panel-heading .btn-success { diff --git a/snprc_ehr/src/client/entryPoints.js b/snprc_ehr/src/client/entryPoints.js index 80a38c37e..5b9d160d5 100644 --- a/snprc_ehr/src/client/entryPoints.js +++ b/snprc_ehr/src/client/entryPoints.js @@ -43,6 +43,12 @@ module.exports = { title: 'Animal Events Webpart', path: './src/client/SndEventsWidget/webpart', generateLib: true + }, + { + name: 'BiocontainmentObservationReview', + title: 'Biocontainment Observation Review', + permissionClasses: ['org.labkey.api.security.permissions.ReadPermission'], + path: './src/client/BiocontainmentObservationReview' } ] }; \ No newline at end of file diff --git a/snprc_ehr/src/org/labkey/snprc_ehr/query/SNPRC_EHRTriggerHelper.java b/snprc_ehr/src/org/labkey/snprc_ehr/query/SNPRC_EHRTriggerHelper.java index e47b46555..635a2b5a5 100644 --- a/snprc_ehr/src/org/labkey/snprc_ehr/query/SNPRC_EHRTriggerHelper.java +++ b/snprc_ehr/src/org/labkey/snprc_ehr/query/SNPRC_EHRTriggerHelper.java @@ -84,6 +84,23 @@ private Container getContainer() return _container; } + /** + * The name printed on an electronic signature: first and last name, or the display name if either is missing, + * or the email if that is empty too. Read from the User object so approvers don't need the + * "See User and Group Details" role that core.Users requires. + */ + public String getPrintedName() + { + String first = _user.getFirstName(); + String last = _user.getLastName(); + if (first != null && !first.isBlank() && last != null && !last.isBlank()) + return first.trim() + " " + last.trim(); + + // Every account has an email, so the signature never records an empty name + String display = _user.getDisplayName(_user); + return display != null && !display.isBlank() ? display : _user.getEmail(); + } + /** * Should we close datasets on animal departure? * diff --git a/snprc_ehr/test/sampledata/study/referenceStudy/study/datasets/datasets_metadata.xml b/snprc_ehr/test/sampledata/study/referenceStudy/study/datasets/datasets_metadata.xml index 63ac5c24d..ad40270f5 100644 --- a/snprc_ehr/test/sampledata/study/referenceStudy/study/datasets/datasets_metadata.xml +++ b/snprc_ehr/test/sampledata/study/referenceStudy/study/datasets/datasets_metadata.xml @@ -3542,6 +3542,29 @@ 80 Comment
+ + integer + Reviewed By + + core + Users + UserId + + + + varchar + 128 + Reviewer Printed Name + + + timestamp + Reviewed Date + + + varchar + 64 + Signature Meaning +