@peopl-health/nexus 5.57.0-dev.9018 → 5.57.0-dev.9027

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -12,6 +12,7 @@ const {
12
12
  getRecommendationCarousels,
13
13
  getRecommendationCarouselImage,
14
14
  } = require('../services/recommendationCarouselService');
15
+ const { recordRecommendationReview } = require('../fhir');
15
16
 
16
17
  const MAX_CONCURRENT_CAROUSEL_IMAGES = 8;
17
18
  let activeCarouselImageRequests = 0;
@@ -72,6 +73,33 @@ const getPatientCarePlanController = async (req, res) => {
72
73
  }
73
74
  };
74
75
 
76
+ // `reviewedBy` is trusted from the caller: the interface derives it from the session.
77
+ const reviewPatientCarePlanCardController = async (req, res) => {
78
+ const code = String(req.params.code || '').trim();
79
+ const recommendationId = String(req.params.cardId || '').trim();
80
+ try {
81
+ if (!code) return res.status(400).json({ success: false, error: 'WhatsApp ID is required' });
82
+ if (!recommendationId) return res.status(400).json({ success: false, error: 'cardId is required' });
83
+
84
+ const { verdict, note = null, correctedText = null, reviewedBy, eventKey = null } = req.body || {};
85
+ const result = await recordRecommendationReview({
86
+ patientId: code, recommendationId, verdict, note, correctedText, reviewedBy, eventKey,
87
+ });
88
+ if (result.skipped) {
89
+ return res.status(503).json({ success: false, error: 'The review was not recorded: writes are suppressed in this scope' });
90
+ }
91
+ if (!result.recorded && !result.duplicate) {
92
+ return res.status(404).json({ success: false, error: 'No card with that id for this patient' });
93
+ }
94
+ return res.status(200).json({ success: true, ...result });
95
+ } catch (error) {
96
+ const isCallerError = /^(invalid |reviewedBy is required|a corrected verdict)/.test(error.message || '');
97
+ if (isCallerError) return res.status(400).json({ success: false, error: error.message });
98
+ logger.error('Error recording care plan review:', { error: error.message, stack: error.stack, code, recommendationId });
99
+ return res.status(500).json({ success: false, error: 'Failed to record the care plan review' });
100
+ }
101
+ };
102
+
75
103
  const getPatientTasksController = async (req, res) => {
76
104
  try {
77
105
  const tasks = await getPatientTasks(req.params.code);
@@ -261,6 +289,7 @@ module.exports = {
261
289
  getPatientInfoController,
262
290
  getPatientTriageInfoController,
263
291
  getPatientCarePlanController,
292
+ reviewPatientCarePlanCardController,
264
293
  getPatientEscalationContextController,
265
294
  getPatientTasksController,
266
295
  getPatientRecommendationCarouselsController,
@@ -88,6 +88,12 @@ const RECOMMENDATION_EXT = {
88
88
  REC_FOLLOWUP_URGENCY: 'recommendation-followup-urgency',
89
89
  PRODUCED_BY_MODEL: 'recommendation-produced-by-model',
90
90
  METHOD_VERSION: 'recommendation-method-version',
91
+ REVIEW_VERDICT: 'recommendation-review-verdict',
92
+ REVIEW_NOTE: 'recommendation-review-note',
93
+ REVIEW_CORRECTED_TEXT: 'recommendation-review-corrected-text',
94
+ REVIEW_BY: 'recommendation-review-by',
95
+ REVIEW_RECORDED_AT: 'recommendation-review-recorded-at',
96
+ REVIEW_EVENT: 'recommendation-review-event',
91
97
  };
92
98
 
93
99
  const SAFETY_GATE_EXT = {
@@ -1,3 +1,5 @@
1
+ const { createHash } = require('crypto');
2
+
1
3
  const { FHIR_ID_MAX } = require('./fhirHelper');
2
4
 
3
5
  const TRIAGE_RUN_PREFIX = 'recrun-triage-';
@@ -9,6 +11,19 @@ const recommendationId = (runId, rank) => {
9
11
  return `${sanitize(runId).slice(0, FHIR_ID_MAX - suffix.length)}${suffix}`;
10
12
  };
11
13
 
14
+ // `recommendationId` fills the id budget, so appending would drop its `-recN` suffix.
15
+ const reviewProvenanceId = (recommendationId, discriminator) => {
16
+ const digest = createHash('sha1').update(`${recommendationId}|${discriminator}`).digest('hex');
17
+ return `rev-${digest.slice(0, 40)}`;
18
+ };
19
+
20
+ // Sanitising alone maps `a_b@` and `a-b@` onto one id.
21
+ const REVIEWER_DIGEST_LENGTH = 12;
22
+ const reviewerId = (reviewer) => {
23
+ const digest = createHash('sha1').update(String(reviewer)).digest('hex').slice(0, REVIEWER_DIGEST_LENGTH);
24
+ return `${sanitize(reviewer).slice(0, FHIR_ID_MAX - digest.length - 1)}-${digest}`;
25
+ };
26
+
12
27
  const runIdOf = (id) => id.replace(/-rec[^-]*$/, '');
13
28
 
14
29
  const rankOf = (id) => {
@@ -20,6 +35,8 @@ const sourceOfRun = (runId) => (runId.startsWith(TRIAGE_RUN_PREFIX) ? 'triage' :
20
35
 
21
36
  module.exports = {
22
37
  recommendationId,
38
+ reviewProvenanceId,
39
+ reviewerId,
23
40
  runIdOf,
24
41
  rankOf,
25
42
  sourceOfRun,
@@ -11,14 +11,17 @@ function baseResource(resourceType, id, slug, patientId = null) {
11
11
  };
12
12
  }
13
13
 
14
- function provenance({ provenanceId, targetRefs, recordedAt, activity, agentDevice = null, onBehalfOf = null }) {
14
+ function provenance({
15
+ provenanceId, targetRefs, recordedAt, activity,
16
+ agentDevice = null, onBehalfOf = null, agentWho = null,
17
+ }) {
15
18
  return {
16
19
  resourceType: 'Provenance',
17
20
  id: fhirId(provenanceId),
18
21
  target: targetRefs,
19
22
  recorded: toIso(recordedAt),
20
23
  agent: [{
21
- who: reference('Device', agentDevice || getDeviceId()),
24
+ who: agentWho || reference('Device', agentDevice || getDeviceId()),
22
25
  onBehalfOf: reference('Organization', onBehalfOf || getOrganizationId()),
23
26
  }],
24
27
  activity,
package/lib/fhir/index.js CHANGED
@@ -12,6 +12,7 @@ const {
12
12
  readActiveRecommendations,
13
13
  readRecommendationPlans,
14
14
  recordRecommendationOutcome,
15
+ recordRecommendationReview,
15
16
  } = require('./services/recommendationService');
16
17
  const { storeContingency, readContingencies } = require('./services/contingencyService');
17
18
  const { readDispatchedEscalations } = require('./services/escalationService');
@@ -65,6 +66,7 @@ module.exports = {
65
66
  readActiveRecommendations,
66
67
  readRecommendationPlans,
67
68
  recordRecommendationOutcome,
69
+ recordRecommendationReview,
68
70
  storeContingency,
69
71
  readContingencies,
70
72
  readDispatchedEscalations,
@@ -9,6 +9,7 @@ const { PALLIATIVE_CAREPLAN_SLUG, PALLIATIVE_CAREPLAN_REC_SLUG } = require('../c
9
9
  const { PALLIATIVE_EXT } = require('../constants/extensionSlugs');
10
10
  const { PalliativeCarePlan } = require('../../shared/dtos/PalliativeCarePlan');
11
11
  const { logger } = require('../../utils/logger');
12
+ const { reviewHistoryOf } = require('./recommendationPlanProjection');
12
13
 
13
14
  const ACTIVITY_TEXT = 'palliative-careplan';
14
15
  const NOTE_SEPARATOR = ': ';
@@ -109,7 +110,17 @@ function fromFhir(resources, { patientId }) {
109
110
  if (resource.resourceType !== 'CarePlan') continue;
110
111
  if (!identifierValue(resource, PALLIATIVE_CAREPLAN_SLUG)) continue;
111
112
  try {
112
- out.push(new PalliativeCarePlan(reconstruct(resource, tasksByReference, patientId)));
113
+ const tasks = recommendationTasks(resource, tasksByReference);
114
+ const carePlan = new PalliativeCarePlan(reconstruct(resource, tasksByReference, patientId));
115
+ // The DTO is strict, so reviews are attached after validation rather than inside it.
116
+ const reviewsByRank = new Map(tasks.map((task) => [
117
+ extMap(task)[PALLIATIVE_EXT.CAREPLAN_REC_RANK],
118
+ reviewHistoryOf(task),
119
+ ]));
120
+ for (const recommendation of carePlan.recommendations) {
121
+ recommendation.reviewHistory = reviewsByRank.get(recommendation.rank) || [];
122
+ }
123
+ out.push(carePlan);
113
124
  } catch (error) {
114
125
  if (error instanceof ZodError) {
115
126
  logger.warn({ careplanId: resource.id }, 'skipping malformed palliative CarePlan');
@@ -121,12 +132,13 @@ function fromFhir(resources, { patientId }) {
121
132
  return out;
122
133
  }
123
134
 
135
+ const recommendationTasks = (plan, tasksByReference) => (plan.activity || [])
136
+ .map((activity) => tasksByReference.get(activity.plannedActivityReference?.reference))
137
+ .filter(Boolean);
138
+
124
139
  function reconstruct(plan, tasksByReference, patientId) {
125
140
  const ext = extMap(plan);
126
- const recommendations = (plan.activity || [])
127
- .map((activity) => tasksByReference.get(activity.plannedActivityReference?.reference))
128
- .filter(Boolean)
129
- .map(reconstructRecommendation);
141
+ const recommendations = recommendationTasks(plan, tasksByReference).map(reconstructRecommendation);
130
142
  return {
131
143
  careplanId: identifierValue(plan, PALLIATIVE_CAREPLAN_SLUG),
132
144
  patientId,
@@ -15,6 +15,8 @@ const {
15
15
  const PROJECTOR_NAME = 'recommendationPlan';
16
16
  const ACTIVITY_TEXT = 'recommendations-process';
17
17
  const OUTCOME_KEY = 'recommendation-outcome';
18
+ const REVIEW_KEY = 'recommendation-review';
19
+ const REVIEW_VERDICTS = ['confirmed', 'corrected', 'rejected'];
18
20
  const NOTE_SEPARATOR = ': ';
19
21
  const CARE_PLAN_CATEGORY = 'symptom_management';
20
22
  const NOTE_LABELS = {
@@ -253,11 +255,64 @@ function outcomeEntry({ outcome, adherence, notes, source, recordedAt, eventKey
253
255
  return entry;
254
256
  }
255
257
 
256
- // A retried run rewrites the same outcome with a new timestamp; the event key is what makes it recognisable.
257
- function hasOutcomeEvent(task, eventKey) {
258
- return (task?.output || []).some((entry) => extMap(entry)[RECOMMENDATION_EXT.OUTCOME_EVENT] === eventKey);
258
+ function reviewEntry({ verdict, note, correctedText, reviewedBy, recordedAt, eventKey }) {
259
+ const entry = {
260
+ type: codeableConcept(REVIEW_KEY),
261
+ valueCodeableConcept: codeableConcept(verdict, { code: verdict, system: codeSystemUrl(REVIEW_KEY) }),
262
+ extension: [
263
+ extension(RECOMMENDATION_EXT.REVIEW_VERDICT, { valueString: verdict }),
264
+ extension(RECOMMENDATION_EXT.REVIEW_BY, { valueString: reviewedBy }),
265
+ extension(RECOMMENDATION_EXT.REVIEW_RECORDED_AT, { valueDateTime: recordedAt }),
266
+ ],
267
+ };
268
+ if (note) entry.extension.push(extension(RECOMMENDATION_EXT.REVIEW_NOTE, { valueString: note }));
269
+ if (correctedText) {
270
+ entry.extension.push(extension(RECOMMENDATION_EXT.REVIEW_CORRECTED_TEXT, { valueString: correctedText }));
271
+ }
272
+ if (eventKey) entry.extension.push(extension(RECOMMENDATION_EXT.REVIEW_EVENT, { valueString: eventKey }));
273
+ return entry;
259
274
  }
260
275
 
276
+ const hasReviewEvent = (task, eventKey) => hasEvent(task, eventKey, RECOMMENDATION_EXT.REVIEW_EVENT);
277
+
278
+ const reviewOf = (entry) => {
279
+ const ext = extMap(entry);
280
+ return {
281
+ verdict: ext[RECOMMENDATION_EXT.REVIEW_VERDICT] || null,
282
+ note: ext[RECOMMENDATION_EXT.REVIEW_NOTE] || null,
283
+ correctedText: ext[RECOMMENDATION_EXT.REVIEW_CORRECTED_TEXT] || null,
284
+ reviewedBy: ext[RECOMMENDATION_EXT.REVIEW_BY] || null,
285
+ recordedAt: ext[RECOMMENDATION_EXT.REVIEW_RECORDED_AT] || null,
286
+ };
287
+ };
288
+
289
+ function reviewByEvent(task, eventKey) {
290
+ const entry = (task?.output || []).find((row) => (
291
+ row.type?.text === REVIEW_KEY && extMap(row)[RECOMMENDATION_EXT.REVIEW_EVENT] === eventKey
292
+ ));
293
+ return entry ? reviewOf(entry) : null;
294
+ }
295
+
296
+ // By `recordedAt`, not insertion order: concurrent writes timestamp before they upsert.
297
+ function reviewHistoryOf(task) {
298
+ return (task.output || [])
299
+ .filter((entry) => entry.type?.text === REVIEW_KEY)
300
+ .map(reviewOf)
301
+ .map((review, index) => ({ review, index, at: Date.parse(review.recordedAt ?? '') }))
302
+ .sort((a, b) => {
303
+ const left = Number.isFinite(a.at) ? a.at : -Infinity;
304
+ const right = Number.isFinite(b.at) ? b.at : -Infinity;
305
+ return left === right ? a.index - b.index : left - right;
306
+ })
307
+ .map(({ review }) => review);
308
+ }
309
+
310
+ function hasEvent(task, eventKey, slug) {
311
+ return (task?.output || []).some((entry) => extMap(entry)[slug] === eventKey);
312
+ }
313
+
314
+ const hasOutcomeEvent = (task, eventKey) => hasEvent(task, eventKey, RECOMMENDATION_EXT.OUTCOME_EVENT);
315
+
261
316
  function outcomeHistoryOf(task) {
262
317
  return (task.output || [])
263
318
  .filter((entry) => entry.type?.text === OUTCOME_KEY)
@@ -396,6 +451,7 @@ function reconstructElement(finding, index, runId, tasksById) {
396
451
  recommendationId: task ? identifierValue(task, RECOMMENDATION_REC_SLUG) : null,
397
452
  latestOutcome: task ? mergedOutcome(task) : null,
398
453
  outcomeHistory: task ? outcomeHistoryOf(task) : [],
454
+ reviewHistory: task ? reviewHistoryOf(task) : [],
399
455
  };
400
456
  }
401
457
 
@@ -492,4 +548,9 @@ module.exports = {
492
548
  outcomeHistoryOf,
493
549
  mergedOutcome,
494
550
  warningRecord,
551
+ reviewEntry,
552
+ hasReviewEvent,
553
+ reviewByEvent,
554
+ reviewHistoryOf,
555
+ REVIEW_VERDICTS,
495
556
  };
@@ -30,7 +30,15 @@ async function storeResources(resources, { store = null, merge = null } = {}) {
30
30
  return { stored };
31
31
  }
32
32
 
33
+ // A plan rewrite reprojects its Tasks with no `output`, where the outcomes and verdicts live.
34
+ const keepTaskOutput = {
35
+ merge: (prior, incoming) => (prior.resourceType === 'Task' && prior.output?.length
36
+ ? { ...incoming, output: prior.output }
37
+ : incoming),
38
+ };
39
+
33
40
  module.exports = {
41
+ keepTaskOutput,
34
42
  registerProjector: registry.register,
35
43
  project,
36
44
  storeResources,
@@ -3,7 +3,7 @@ const { PALLIATIVE_ASSESSMENT_SLUG, PALLIATIVE_CAREPLAN_SLUG } = require('../con
3
3
  const { getFhirStore } = require('../stores/fhirStore');
4
4
  const { toFhir: assessmentToFhir, fromFhir: assessmentFromFhir } = require('../projections/palliativeProjection');
5
5
  const { toFhir: carePlanToFhir, fromFhir: carePlanFromFhir } = require('../projections/palliativeCarePlanProjection');
6
- const { storeResources } = require('./fhirService');
6
+ const { storeResources, keepTaskOutput } = require('./fhirService');
7
7
 
8
8
  async function storePalliativeAssessment({ patientId, assessment }) {
9
9
  if (assessment.patientId !== patientId) {
@@ -40,7 +40,7 @@ async function storePalliativeCarePlan({ patientId, carePlan }) {
40
40
  if (carePlan.patientId !== patientId) {
41
41
  throw new Error(`storePalliativeCarePlan patientId mismatch: expected ${patientId}`);
42
42
  }
43
- const { stored } = await storeResources(carePlanToFhir(carePlan));
43
+ const { stored } = await storeResources(carePlanToFhir(carePlan), keepTaskOutput);
44
44
  return { count: stored.length, ids: stored };
45
45
  }
46
46
 
@@ -1,7 +1,11 @@
1
+ const { randomUUID } = require('crypto');
2
+
1
3
  const { fhirId, identifierSystem } = require('../helpers/fhirHelper');
4
+ const { reference, codeableConcept, patientReference } = require('../helpers/elementHelper');
5
+ const { provenance } = require('../helpers/resourceHelper');
2
6
  const { toIso } = require('../helpers/elementHelper');
3
7
  const { identifierValue } = require('../helpers/fhirReadHelper');
4
- const { runIdOf, rankOf, sourceOfRun } = require('../helpers/recommendationIds');
8
+ const { runIdOf, rankOf, sourceOfRun, reviewProvenanceId, reviewerId } = require('../helpers/recommendationIds');
5
9
  const { keyOf, aliasClosure } = require('../helpers/symptomAliasHelper');
6
10
  const {
7
11
  toFhir,
@@ -11,15 +15,20 @@ const {
11
15
  outcomeEntry,
12
16
  hasOutcomeEvent,
13
17
  mergedOutcome,
18
+ reviewEntry,
19
+ hasReviewEvent,
20
+ reviewByEvent,
21
+ REVIEW_VERDICTS,
14
22
  } = require('../projections/recommendationPlanProjection');
15
23
  const {
16
24
  RECOMMENDATION_PLAN_SLUG,
17
25
  RECOMMENDATION_ELEMENTS_SLUG,
18
26
  RECOMMENDATION_REC_SLUG,
27
+ PALLIATIVE_CAREPLAN_REC_SLUG,
19
28
  } = require('../constants/projectionSlugs');
20
29
  const { getFhirStore } = require('../stores/fhirStore');
21
30
  const { logger } = require('../../utils/logger');
22
- const { storeResources } = require('./fhirService');
31
+ const { storeResources, keepTaskOutput } = require('./fhirService');
23
32
  const { safetyGateExists } = require('./riskService');
24
33
  const { getCatalog } = require('./terminologyService');
25
34
 
@@ -37,6 +46,7 @@ async function storeRecommendationPlan({
37
46
  const hasSafetyGate = await safetyGateExists({ runId: plan.runId });
38
47
  const { stored } = await storeResources(
39
48
  toFhir({ plan, hasSafetyGate, anchorAgainst, qualityWarnings, producedBy }),
49
+ keepTaskOutput,
40
50
  );
41
51
  return { count: stored.length, ids: stored };
42
52
  }
@@ -169,11 +179,109 @@ async function recordRecommendationOutcome({
169
179
  };
170
180
  }
171
181
 
182
+ const REVIEW_ACTIVITY = 'recommendation-review';
183
+ const REVIEW_TEXT_MAX = 4000;
184
+ const REVIEW_KEY_MAX = 200;
185
+ // RFC 5321 allows 254 characters for an address.
186
+ const REVIEWER_MAX = 254;
187
+
188
+ function optionalText(value, field, max) {
189
+ if (value === null || value === undefined) return null;
190
+ if (typeof value !== 'string') throw new Error(`invalid ${field}: must be a string when present.`);
191
+ const trimmed = value.trim();
192
+ if (!trimmed) return null;
193
+ if (trimmed.length > max) throw new Error(`invalid ${field}: must be at most ${max} characters.`);
194
+ return trimmed;
195
+ }
196
+
197
+ async function recordRecommendationReview({
198
+ patientId, recommendationId, verdict, note = null,
199
+ correctedText = null, reviewedBy, eventKey = null,
200
+ }) {
201
+ if (!REVIEW_VERDICTS.includes(verdict)) {
202
+ throw new Error(`invalid verdict: ${JSON.stringify(verdict)}. Must be one of ${JSON.stringify(REVIEW_VERDICTS)}.`);
203
+ }
204
+ if (reviewedBy !== null && reviewedBy !== undefined && typeof reviewedBy !== 'string') {
205
+ throw new Error('invalid reviewedBy: must be a string when present.');
206
+ }
207
+ const reviewer = optionalText(reviewedBy, 'reviewedBy', REVIEWER_MAX);
208
+ if (!reviewer) throw new Error('reviewedBy is required: a review with no reviewer is not a review.');
209
+ const reviewNote = optionalText(note, 'note', REVIEW_TEXT_MAX);
210
+ const correction = optionalText(correctedText, 'correctedText', REVIEW_TEXT_MAX);
211
+ const key = optionalText(eventKey, 'eventKey', REVIEW_KEY_MAX);
212
+ if (verdict === 'corrected' && !correction) {
213
+ throw new Error('a corrected verdict requires correctedText: naming the correction is the point.');
214
+ }
215
+
216
+ const target = await resolveTask({ patientId, recommendationId });
217
+ if (!target) return { recorded: false };
218
+
219
+ const recordedAt = toIso(new Date());
220
+ const output = reviewEntry({
221
+ verdict, note: reviewNote, correctedText: correction, reviewedBy: reviewer, recordedAt, eventKey: key,
222
+ });
223
+ const provenanceId = reviewProvenanceId(target.recommendationId, key || `${recordedAt}|${randomUUID()}`);
224
+ let duplicate = false;
225
+ let retained = null;
226
+ const write = await storeResources([target.task], {
227
+ merge: (prior, incoming) => {
228
+ duplicate = Boolean(key) && hasReviewEvent(prior, key);
229
+ if (duplicate) {
230
+ retained = reviewByEvent(prior, key);
231
+ return { ...incoming, output: prior.output };
232
+ }
233
+ return { ...incoming, output: [...(prior.output || []), output] };
234
+ },
235
+ });
236
+ if (write.skipped) return { recorded: false, skipped: write.skipped, recommendation_id: target.recommendationId };
237
+ const stored = {
238
+ verdict: retained?.verdict ?? verdict,
239
+ note: retained ? retained.note : reviewNote,
240
+ correctedText: retained ? retained.correctedText : correction,
241
+ reviewedBy: retained?.reviewedBy ?? reviewer,
242
+ recordedAt: retained?.recordedAt ?? recordedAt,
243
+ };
244
+
245
+ // Runs on the duplicate path too: a retry must still repair a Provenance that never landed.
246
+ const store = getFhirStore();
247
+ if (!await store.getByReference(`Provenance/${fhirId(provenanceId)}`)) {
248
+ await storeResources([provenance({
249
+ provenanceId,
250
+ targetRefs: [{ reference: `Task/${fhirId(target.recommendationId)}` }],
251
+ recordedAt: stored.recordedAt,
252
+ activity: codeableConcept(REVIEW_ACTIVITY),
253
+ agentWho: { ...reference('Practitioner', reviewerId(stored.reviewedBy)), display: stored.reviewedBy },
254
+ })]);
255
+ }
256
+
257
+ return {
258
+ recorded: !duplicate,
259
+ duplicate,
260
+ recommendation_id: target.recommendationId,
261
+ verdict: stored.verdict,
262
+ note: stored.note,
263
+ corrected_text: stored.correctedText,
264
+ reviewed_by: stored.reviewedBy,
265
+ recorded_at: stored.recordedAt,
266
+ };
267
+ }
268
+
269
+ // A card id reaches this code straight from a URL, so it is not proof of access.
270
+ const belongsToPatient = (task, patientId) => task?.for?.reference === patientReference(patientId).reference;
271
+
272
+ const cardIdOf = (task) => identifierValue(task, RECOMMENDATION_REC_SLUG)
273
+ || identifierValue(task, PALLIATIVE_CAREPLAN_REC_SLUG)
274
+ || null;
275
+
172
276
  async function resolveTask({ patientId, recommendationId, ctcaeTerm }) {
173
277
  const store = getFhirStore();
174
278
  if (recommendationId) {
175
279
  const task = await store.getByReference(`Task/${fhirId(recommendationId)}`);
176
- return task ? { task, recommendationId: identifierValue(task, RECOMMENDATION_REC_SLUG) || recommendationId } : null;
280
+ if (!task || !belongsToPatient(task, patientId)) return null;
281
+ // `fhirId()` is lossy, so a mangled or over-long id can normalise onto a real card.
282
+ const cardId = cardIdOf(task);
283
+ if (cardId !== recommendationId) return null;
284
+ return { task, recommendationId: cardId };
177
285
  }
178
286
  const termKeys = filterKeysFor(ctcaeTerm);
179
287
  if (!termKeys) return null;
@@ -181,7 +289,8 @@ async function resolveTask({ patientId, recommendationId, ctcaeTerm }) {
181
289
  const match = active.recommendations.find((item) => item.symptoms.some((symptom) => termKeys.has(keyOf(symptom))));
182
290
  if (!match) return null;
183
291
  const task = await store.getByReference(`Task/${fhirId(match.recommendation_id)}`);
184
- return task ? { task, recommendationId: match.recommendation_id } : null;
292
+ if (!task || !belongsToPatient(task, patientId)) return null;
293
+ return { task, recommendationId: match.recommendation_id };
185
294
  }
186
295
 
187
296
  function reconstructRecommendation(task, recommendationId, runId, isActive) {
@@ -205,6 +314,7 @@ function reconstructRecommendation(task, recommendationId, runId, isActive) {
205
314
 
206
315
  module.exports = {
207
316
  storeRecommendationPlan,
317
+ recordRecommendationReview,
208
318
  recommendationPlanExists,
209
319
  readActiveRecommendations,
210
320
  readRecommendationPlans,
@@ -27,7 +27,9 @@ class FhirStore {
27
27
  const resourceKey = model.resourceKeyOf(incoming);
28
28
  for (let attempt = 0; attempt < UPSERT_ATTEMPTS; attempt++) {
29
29
  const priorVersion = await model.findOne({ resourceKey }).lean();
30
- const resource = merge && priorVersion ? this._toStoredResource(merge(priorVersion.resource, incoming)) : incoming;
30
+ // Every merge reads `prior` as the live resource, and an upsert clears the tombstone.
31
+ const mergeable = priorVersion && !priorVersion.meta.deleted;
32
+ const resource = merge && mergeable ? this._toStoredResource(merge(priorVersion.resource, incoming)) : incoming;
31
33
  if (resource !== incoming && model.resourceKeyOf(resource) !== resourceKey) {
32
34
  throw new Error(`merge changed the resource key for ${resourceKey}`);
33
35
  }
@@ -70,6 +70,7 @@ const patientRouteDefinitions = {
70
70
  'GET /:code': 'getPatientInfoController',
71
71
  'GET /triage/:code': 'getPatientTriageInfoController',
72
72
  'GET /careplan/:code': 'getPatientCarePlanController',
73
+ 'PATCH /careplan/:code/cards/:cardId/review': 'reviewPatientCarePlanCardController',
73
74
  'GET /escalation-context/:code': 'getPatientEscalationContextController',
74
75
  'GET /tasks/:code': 'getPatientTasksController',
75
76
  'PATCH /:code': 'updatePatientController',
@@ -233,6 +234,7 @@ const builtInControllers = {
233
234
  getPatientInfoController: patientController.getPatientInfoController,
234
235
  getPatientTriageInfoController: patientController.getPatientTriageInfoController,
235
236
  getPatientCarePlanController: patientController.getPatientCarePlanController,
237
+ reviewPatientCarePlanCardController: patientController.reviewPatientCarePlanCardController,
236
238
  getPatientEscalationContextController: patientController.getPatientEscalationContextController,
237
239
  getPatientTasksController: patientController.getPatientTasksController,
238
240
  getPatientRecommendationCarouselsController: patientController.getPatientRecommendationCarouselsController,
@@ -30,7 +30,10 @@ const DEFAULT_LIMIT = 20;
30
30
  const FAILED_CURRENT_STATE = Symbol('currentStateUnavailable');
31
31
  const ESCALATION_LOOKBACK_MS = 365 * 24 * 60 * 60 * 1000;
32
32
 
33
- const cardOf = ({ id, rank, nameShort, type, ctcaeTerms, patient, internal, outcome = null, outcomeHistory = [] }) => ({
33
+ const cardOf = ({
34
+ id, rank, nameShort, type, ctcaeTerms, patient, internal,
35
+ outcome = null, outcomeHistory = [], reviewHistory = [],
36
+ }) => ({
34
37
  id,
35
38
  rank,
36
39
  nameShort,
@@ -40,6 +43,7 @@ const cardOf = ({ id, rank, nameShort, type, ctcaeTerms, patient, internal, outc
40
43
  internal,
41
44
  outcome,
42
45
  outcomeHistory,
46
+ reviewHistory,
43
47
  });
44
48
 
45
49
  const emptyEscalation = { urgentUnder24h: false, maxActionTimeHours: null, routes: [], clinicalCriteria: null };
@@ -98,6 +102,7 @@ function recommendationCards(plan) {
98
102
  },
99
103
  outcome: element.latestOutcome,
100
104
  outcomeHistory: element.outcomeHistory,
105
+ reviewHistory: element.reviewHistory || [],
101
106
  }));
102
107
  }
103
108
 
@@ -143,6 +148,7 @@ function palliativeCards(carePlan, findingsByRank) {
143
148
  auditNotes: finding?.auditNotes ?? null,
144
149
  clusterNote: finding?.clusterNote ?? null,
145
150
  },
151
+ reviewHistory: recommendation.reviewHistory || [],
146
152
  });
147
153
  });
148
154
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.57.0-dev.9018",
3
+ "version": "5.57.0-dev.9027",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",