@peopl-health/nexus 5.72.0-dev.13744 → 5.72.0-dev.14094

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.
@@ -1,9 +1,11 @@
1
1
  const { foldAccents } = require('../../utils/formatUtils');
2
2
 
3
3
  const MAX_ALIAS_WORDS = 4;
4
- const PART_SEPARATORS = /\s*(?:\+|±|,|;|\/|\(|\)|\by\b|\bcon\b)\s*/;
4
+ const PART_SEPARATORS = /\s*(?:\+|±|,|;|\/|\(|\)|\by\b|\bcon\b|\bm[aá]s\b|\bplus\b)\s*/i;
5
5
  // a dose or a route left between separators ("100 MG / 20 ML en 500 ML glucosado", "IV/SC") names no drug
6
6
  const DOSE_OR_ROUTE = /^(\d+|iv|sc|im|vo|po|ev|mg|ml|mcg|ui)(\s|$)/;
7
+ // beside a drug, only a dose, a route, or how it is formulated or scheduled says nothing about another drug
8
+ const DOSE_OR_ROUTE_WORD = /^(\d+(mg|ml|mcg|g|ui)?|iv|sc|im|vo|po|ev|mg|ml|mcg|ui|g)$/;
7
9
 
8
10
  // one key for a brand, a Spanish and an English spelling: ciclofosfamida and cyclophosphamide meet
9
11
  const drugKey = (name) => foldAccents(String(name ?? '')).toLowerCase()
@@ -14,6 +16,9 @@ const drugKey = (name) => foldAccents(String(name ?? '')).toLowerCase()
14
16
  .replace(/\s+/g, ' ')
15
17
  .trim();
16
18
 
19
+ const FORM_OR_SCHEDULE = new Set(['monodroga', 'semanal', 'liposomal', 'pegilada', 'lar', 'depot', 'pfs', 'jeringa'].map(drugKey));
20
+ const describesDose = (word) => DOSE_OR_ROUTE_WORD.test(word) || FORM_OR_SCHEDULE.has(word);
21
+
17
22
  const lines = (text) => String(text ?? '').split(/[\n,;]+/).map((line) => line.trim()).filter(Boolean);
18
23
 
19
24
  function buildDrugIdentity(catalog) {
@@ -34,24 +39,26 @@ function buildDrugIdentity(catalog) {
34
39
 
35
40
  function genericsInPart(words, identity) {
36
41
  const found = new Set();
42
+ let stray = false;
37
43
  for (let at = 0; at < words.length;) {
38
44
  let span = Math.min(MAX_ALIAS_WORDS, words.length - at);
39
45
  for (; span > 0 && !identity.aliases.has(words.slice(at, at + span).join(' ')); span -= 1);
40
46
  if (span) found.add(identity.aliases.get(words.slice(at, at + span).join(' ')));
47
+ else if (!describesDose(words[at])) stray = true;
41
48
  at += span || 1;
42
49
  }
43
- return found;
50
+ return { found, stray };
44
51
  }
45
52
 
46
- // every drug the text names; unresolved when some part of it names none the catalog knows
53
+ // every drug the text names; unresolved when some part names none the catalog knows, or names one beside an unknown word
47
54
  function drugsNamed(text, identity) {
48
55
  const whole = identity.aliases.get(drugKey(text));
49
56
  if (whole) return { drugs: [identity.generics.get(whole)], unresolved: false };
50
57
  const keys = new Set();
51
58
  let unresolved = false;
52
59
  for (const part of String(text ?? '').split(PART_SEPARATORS).map(drugKey).filter(Boolean)) {
53
- const found = genericsInPart(part.split(' '), identity);
54
- if (!found.size && !DOSE_OR_ROUTE.test(part)) unresolved = true;
60
+ const { found, stray } = genericsInPart(part.split(' '), identity);
61
+ if (found.size ? stray : !DOSE_OR_ROUTE.test(part)) unresolved = true;
55
62
  found.forEach((key) => keys.add(key));
56
63
  }
57
64
  return { drugs: [...keys].map((key) => identity.generics.get(key)), unresolved: unresolved || !keys.size };
@@ -156,7 +156,13 @@ async function extractClinicalMentions({ text, turnId, code, provider, detectedT
156
156
  const patientMentions = [...clinicalMentions, ...pendingMentions]
157
157
  .filter((mention) => mention.fact.assertion.experiencer === 'patient');
158
158
  if (persist && patientMentions.length) {
159
- await storeClinicalMentions({ patientId: code, mentions: patientMentions });
159
+ // A store failure must not discard what was extracted: the turn still routes on these facts.
160
+ try {
161
+ await storeClinicalMentions({ patientId: code, mentions: patientMentions });
162
+ } catch (err) {
163
+ logger.error('[clinicalExtraction] storing the mentions in FHIR failed (may be partially stored); the turn keeps them', { turnId, mentions: patientMentions.length, error: err?.message });
164
+ trace?.setSignals?.({ clinicalMentionsStoreFailed: true });
165
+ }
160
166
  }
161
167
 
162
168
  return {
@@ -1,4 +1,4 @@
1
- const { readContingencies, readClusters, storeCluster } = require('../../fhir');
1
+ const { closeRoutingDispositions, readContingencies, readClusters, storeCluster } = require('../../fhir');
2
2
  const { RESOLUTION_CLOSE_REASONS } = require('../../shared/dtos/ManagedSymptom');
3
3
  const { RESOLVED_REASONS } = require('../../shared/dtos/ContingencySafetyNet');
4
4
  const { ClusterImpression } = require('../../shared/dtos/ClusterImpression');
@@ -58,7 +58,7 @@ function closePatch({ closeReason, resolving, reasoning }) {
58
58
  };
59
59
  }
60
60
 
61
- async function runCloseCascade(patientId, caseId, turnId, trace = null, sourceTool = 'updateConditionStatus') {
61
+ async function runCloseCascade(patientId, caseId, turnId, trace, sourceTool, { closeReason }) {
62
62
  const autoResolvedPlans = [];
63
63
  const prunedClusters = [];
64
64
  const dissolvedClusters = [];
@@ -74,6 +74,12 @@ async function runCloseCascade(patientId, caseId, turnId, trace = null, sourceTo
74
74
  cascadeErrors.push(`contingency_auto_resolve_failed: ${error?.message || error}`);
75
75
  }
76
76
 
77
+ try {
78
+ await closeRoutingDispositions({ patientId, caseId, closeReason, resolving: isResolutionReason(closeReason) });
79
+ } catch (error) {
80
+ cascadeErrors.push(`routing_disposition_close_failed: ${error?.message || error}`);
81
+ }
82
+
77
83
  const clusters = await readClusters({ patientId, status: 'active' }).catch((error) => {
78
84
  cascadeErrors.push(`cluster_cascade_failed: ${error?.message || error}`);
79
85
  return [];
@@ -6,27 +6,38 @@ const { Quimio_Ops_ID } = require('../../config/airtableConfig');
6
6
  const { MATCH_ALL } = require('../../helpers/airtableFormulaHelper');
7
7
  const { readContextFacts, listContextFactPatients } = require('../../fhir');
8
8
  const { mapConcurrent } = require('../../utils/concurrencyUtils');
9
- const { mexicoDay } = require('../../utils/dateUtils');
9
+ const { daysBetween, mexicoDay } = require('../../utils/dateUtils');
10
10
  const { maskSensitiveValue } = require('../../utils/sanitizerUtils');
11
11
  const { logger } = require('../../utils/logger');
12
12
 
13
13
  const CATALOG_TABLE = 'catalogo_farmacos';
14
14
  const CATALOG_FIELDS = ['farmaco', 'variantes', 'generico', 'grupo'];
15
- const ACTIVE_WINDOW_DAYS = 100;
15
+ // the oncology sign-off of 2026-10-14 sets these windows and lists
16
+ const LAST_APPLICATION_DAYS = 60;
17
+ const REGIMEN_MIN_DAYS = 21;
18
+ // a checkpoint inhibitor is often given every 6 weeks, or held for an immune toxicity
19
+ const CHECKPOINT_REGIMEN_MIN_DAYS = 84;
16
20
  const INJECTABLE_VARIABLE = 'injectable_onco_summary';
17
- const CURRENT_STATUSES = new Set([null, 'taking', 'unknown', 'on-hold']);
21
+ const CURRENT_STATUSES = new Set([null, 'taking', 'unknown']);
18
22
  const PROPOSED_STATUS = 'stopped';
19
23
  // the unit's catalog files support care and premedication apart; only its own antineoplastics are closed
20
24
  const CLOSABLE_GROUP = 'Quimioterapia';
21
- // in that group but oral, a hormone depot, or given outside the unit: pending oncology sign-off
25
+ // in that group but oral, a hormone depot, a rescue or protector, or given outside the unit
22
26
  const NEVER_CLOSED = new Set([
23
- 'capecitabina', 'darolutamida', 'degarelix', 'fulvestrant', 'goserelina', 'leuprorelina', 'lanreotida',
24
- 'octreotida', 'bacilo de Calmette-Guérin', 'ácido folínico',
27
+ 'capecitabina', 'darolutamida', 'degarelix', 'fulvestrant', 'goserelina', 'leuprorelina', 'triptorelina',
28
+ 'histrelina', 'buserelina', 'lanreotida', 'octreotida', 'pasireotida', 'bacilo de Calmette-Guérin', 'ácido folínico',
29
+ 'levofolinato', 'mesna', 'dexrazoxano',
30
+ ].map(drugKey));
31
+ const CHECKPOINT_INHIBITORS = new Set([
32
+ 'pembrolizumab', 'nivolumab', 'atezolizumab', 'durvalumab', 'avelumab', 'cemiplimab', 'dostarlimab',
33
+ 'tislelizumab', 'toripalimab', 'retifanlimab', 'sintilimab', 'camrelizumab', 'serplulimab', 'cosibelimab',
34
+ 'ipilimumab', 'tremelimumab',
25
35
  ].map(drugKey));
26
36
  const DEFAULT_PATIENT_CONCURRENCY = 10;
27
37
 
28
38
  // a co-formulation such as pertuzumab/trastuzumab is each of its drugs
29
39
  const keysOf = (drug) => drug.generic.split('/').map(drugKey);
40
+ const isCheckpoint = (key) => CHECKPOINT_INHIBITORS.has(key);
30
41
  const closable = (drug) => drug.group === CLOSABLE_GROUP && !NEVER_CLOSED.has(drugKey(drug.generic));
31
42
  // the day as stated: a date-only report is stored at UTC midnight, which Mexico time would move to the day before
32
43
  const dayOf = (row) => {
@@ -39,13 +50,15 @@ async function loadDrugIdentity() {
39
50
  return catalog?.length ? buildDrugIdentity(catalog) : null;
40
51
  }
41
52
 
42
- function skipReason(row, { chemo, identity, regimen }) {
53
+ function skipReason(row, { chemo, identity, regimen, regimenDays, replacedInClass }) {
43
54
  const named = drugsNamed(row.concept ?? row.value, identity);
44
55
  if (named.unresolved) return 'unresolved';
45
56
  if (named.drugs.flatMap(keysOf).some((key) => regimen.has(key))) return 'in-regimen';
46
57
  if (!named.drugs.every(closable)) return 'never-closed';
47
58
  const since = dayOf(row);
48
59
  if (!since || since >= chemo.inicioEsquema.fecha) return 'not-before-regimen';
60
+ const checkpoint = named.drugs.flatMap(keysOf).some(isCheckpoint);
61
+ if (checkpoint && !replacedInClass && regimenDays < CHECKPOINT_REGIMEN_MIN_DAYS) return 'checkpoint-too-recent';
49
62
  return null;
50
63
  }
51
64
 
@@ -62,10 +75,15 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
62
75
  const none = (reason) => ({ closures: [], skipped: { [reason]: 1 } });
63
76
  if (chemo === undefined) return none('chemo-unreadable');
64
77
  if (!chemo?.inicioEsquema) return none('no-regimen-start');
65
- const status = chemoStatus(chemo, today, ACTIVE_WINDOW_DAYS);
78
+ const status = chemoStatus(chemo, today, LAST_APPLICATION_DAYS);
66
79
  if (!status.active) return none('inactive');
67
80
  // a scheduled session keeps a regimen active, but an old last application is no evidence of what it is now
68
- if (status.days > ACTIVE_WINDOW_DAYS) return none('stale-regimen');
81
+ if (status.days > LAST_APPLICATION_DAYS) return none('stale-regimen');
82
+ // a drug given on day 8 or every three weeks may not have come up yet in a younger regimen
83
+ const regimenDays = daysBetween(chemo.inicioEsquema.fecha, today);
84
+ if (regimenDays < REGIMEN_MIN_DAYS) return none('regimen-too-recent');
85
+ // without a previous regimen the start is only the first recorded session, so a second one must show the regimen
86
+ if (!chemo.esquemaPrevio && !(chemo.ultimaAplicacion.fecha > chemo.inicioEsquema.fecha)) return none('single-session-regimen');
69
87
  const named = chemo.esquema.map((entry) => drugsNamed(entry.farmaco, identity));
70
88
  // a drug of the regimen the catalog cannot name could be the very drug of a slot
71
89
  if (named.some((entry) => entry.unresolved)) return none('unresolved-regimen');
@@ -73,11 +91,12 @@ function proposeClosures({ chemo, facts, identity, today = mexicoDay(new Date())
73
91
  // a depot or support visit is no evidence the antineoplastic line changed
74
92
  if (!regimenDrugs.some(closable)) return none('no-closable-regimen');
75
93
  const regimen = new Set(regimenDrugs.flatMap(keysOf));
94
+ const replacedInClass = [...regimen].some(isCheckpoint);
76
95
  const closures = [];
77
96
  const skipped = {};
78
97
  for (const row of facts) {
79
98
  if (row.variableId !== INJECTABLE_VARIABLE || !CURRENT_STATUSES.has(row.status ?? null)) continue;
80
- const reason = skipReason(row, { chemo, identity, regimen });
99
+ const reason = skipReason(row, { chemo, identity, regimen, regimenDays, replacedInClass });
81
100
  if (reason) {
82
101
  skipped[reason] = (skipped[reason] ?? 0) + 1;
83
102
  continue;
@@ -321,7 +321,9 @@ async function handler(args = {}, context = {}) {
321
321
  const dissolvedClusters = [];
322
322
  if (event === 'close') {
323
323
  try {
324
- const cascade = await runCloseCascade(patientId, caseId, runtime.turnId, runtime.trace || null, 'recordClinicalImpression');
324
+ const cascade = await runCloseCascade(patientId, caseId, runtime.turnId, runtime.trace || null, 'recordClinicalImpression', {
325
+ closeReason: result.condition.closeReason,
326
+ });
325
327
  autoResolvedPlans.push(...cascade.autoResolvedPlans);
326
328
  prunedClusters.push(...cascade.prunedClusters);
327
329
  dissolvedClusters.push(...cascade.dissolvedClusters);
@@ -3,7 +3,9 @@ const crypto = require('node:crypto');
3
3
  const { clinicalIntakeRequiresRisk, hasAlternateTerminalCommit, validateRoutingPrerequisites } = require('../helpers/clinicalWorkflowGuard');
4
4
  const { MEDICATION_NAMING_RULE } = require('../helpers/medicationNamingRule');
5
5
  const { attachRequiredSkill } = require('../helpers/skillActivationHelper');
6
- const { storeRoutingDecision, readRoutingDecisions, readSymptomCases } = require('../../fhir');
6
+ const { isResolutionReason } = require('../services/conditionCloseService');
7
+ const { closeRoutingDispositions, storeRoutingDecision, readRoutingDecisions, readSymptomCases } = require('../../fhir');
8
+ const { CLOSED_STATUSES } = require('../../shared/dtos/ManagedSymptom');
7
9
  const { RoutingDecision } = require('../../shared/dtos/RoutingDecision');
8
10
  const { foldAccents } = require('../../utils/formatUtils');
9
11
  const { logger } = require('../../utils/logger');
@@ -49,6 +51,20 @@ const _COMPOSE_SYNONYMS = {
49
51
  separate: 'separate_if_space',
50
52
  };
51
53
 
54
+ // The case is already closed (often earlier this same turn): its disposition is born closed, as the cascade
55
+ // would have left it.
56
+ async function closeDispositionForClosedCase({ patientId, turnId, caseId, cases }) {
57
+ const condition = caseId ? cases.find((c) => c.condition.conditionId === caseId)?.condition : null;
58
+ if (!CLOSED_STATUSES.includes(condition?.clinicalStatus) || !condition.closeReason) return;
59
+ try {
60
+ await closeRoutingDispositions({
61
+ patientId, caseId, closeReason: condition.closeReason, resolving: isResolutionReason(condition.closeReason),
62
+ });
63
+ } catch (error) {
64
+ logger.warn('[submitRoutingDecision] could not close the disposition of an already-closed case', { patientId, turnId, caseId, error: error?.message });
65
+ }
66
+ }
67
+
52
68
  const _ACTION_TO_DISPOSITION_KIND = {
53
69
  emergency_escalation: 'task',
54
70
  team_escalation: 'task',
@@ -398,8 +414,9 @@ async function handler(args = {}, context = {}) {
398
414
  }
399
415
 
400
416
  const namedCaseIds = [...new Set([...traceResult.findings.map((f) => f.caseId), plan.primaryCaseId].filter(Boolean))];
417
+ let cases = [];
401
418
  if (namedCaseIds.length) {
402
- const cases = await readSymptomCases({ patientId });
419
+ cases = await readSymptomCases({ patientId });
403
420
  const known = new Set(cases.map((c) => c.condition.conditionId));
404
421
  const unknown = namedCaseIds.filter((id) => !known.has(id));
405
422
  if (unknown.length) {
@@ -417,6 +434,7 @@ async function handler(args = {}, context = {}) {
417
434
 
418
435
  const decision = buildDecision({ patientId, turnId, plan, findings: traceResult.findings, now: new Date().toISOString() });
419
436
  await storeRoutingDecision({ patientId, routingDecision: decision });
437
+ await closeDispositionForClosedCase({ patientId, turnId, caseId: plan.primaryCaseId, cases });
420
438
 
421
439
  runtime.trace.setSignals({ branchTaken: 'ai_agent' });
422
440
 
@@ -165,7 +165,9 @@ async function handler(args = {}, context = {}) {
165
165
  const result = applyDormant(existing, reasoning, args, transition === 'resolve');
166
166
  if (typeof result === 'string') return result;
167
167
  await storeSymptomCase({ patientId, managedSymptom: result });
168
- const cascade = await runCloseCascade(patientId, result.condition.conditionId, runtime.turnId, runtime.trace || null);
168
+ const cascade = await runCloseCascade(patientId, result.condition.conditionId, runtime.turnId, runtime.trace || null, 'updateConditionStatus', {
169
+ closeReason: result.condition.closeReason,
170
+ });
169
171
  const data = {
170
172
  case_id: result.condition.conditionId,
171
173
  status: returnedStatus(result.condition),
@@ -1,5 +1,7 @@
1
1
  const { fhirId, identifierSystem, extensionUrl } = require('./fhirHelper');
2
2
 
3
+ const EXTENSION_KEYS = new Set(['extension', 'modifierExtension']);
4
+
3
5
  function identifier(slug, value) {
4
6
  return { system: identifierSystem(slug), value };
5
7
  }
@@ -46,6 +48,25 @@ function toIso(value) {
46
48
  return `${s}Z`;
47
49
  }
48
50
 
51
+ // FHIR ele-1/ext-1: no element may be empty or null, and an extension needs a value or child extensions.
52
+ function pruneEmptyElements(resource) {
53
+ const prune = (value, parentKey) => {
54
+ if (value === null || value === undefined || value === '') return undefined;
55
+ if (Array.isArray(value)) {
56
+ const items = value.map((item) => prune(item, parentKey)).filter((item) => item !== undefined);
57
+ return items.length ? items : undefined;
58
+ }
59
+ if (typeof value !== 'object') return value;
60
+ const entries = Object.entries(value)
61
+ .map(([key, child]) => [key, prune(child, key)])
62
+ .filter(([, child]) => child !== undefined);
63
+ if (!entries.length) return undefined;
64
+ if (EXTENSION_KEYS.has(parentKey) && entries.every(([key]) => key === 'url')) return undefined;
65
+ return Object.fromEntries(entries);
66
+ };
67
+ return prune(resource, null) ?? {};
68
+ }
69
+
49
70
  module.exports = {
50
71
  identifier,
51
72
  reference,
@@ -56,4 +77,5 @@ module.exports = {
56
77
  notes,
57
78
  toInstant,
58
79
  toIso,
80
+ pruneEmptyElements,
59
81
  };
@@ -343,4 +343,5 @@ module.exports = {
343
343
  ordinalValue,
344
344
  codingsFor,
345
345
  gradeConcept,
346
+ ctcaeSlug,
346
347
  };
package/lib/fhir/index.js CHANGED
@@ -15,10 +15,10 @@ const {
15
15
  recordRecommendationReview,
16
16
  } = require('./services/recommendationService');
17
17
  const { storeContingency, readContingencies } = require('./services/contingencyService');
18
- const { readDispatchedEscalations, storeEscalationCase } = require('./services/escalationService');
18
+ const { readDispatchedEscalations, readEscalationCases, storeEscalationCase } = require('./services/escalationService');
19
19
  const { storeIntervention, readInterventions } = require('./services/interventionService');
20
20
  const { storeCluster, readClusters } = require('./services/clusterService');
21
- const { storeRoutingDecision, readRoutingDecisions } = require('./services/routingService');
21
+ const { closeRoutingDispositions, storeRoutingDecision, readRoutingDecisions } = require('./services/routingService');
22
22
  const {
23
23
  storePalliativeAssessment,
24
24
  readPalliativeAssessments,
@@ -71,10 +71,12 @@ module.exports = {
71
71
  readContingencies,
72
72
  readDispatchedEscalations,
73
73
  storeEscalationCase,
74
+ readEscalationCases,
74
75
  storeIntervention,
75
76
  readInterventions,
76
77
  storeCluster,
77
78
  readClusters,
79
+ closeRoutingDispositions,
78
80
  storeRoutingDecision,
79
81
  readRoutingDecisions,
80
82
  storePalliativeAssessment,
@@ -1,6 +1,7 @@
1
1
  const { getDeviceId, getOrganizationId, getSystems } = require('../config/fhirConfig');
2
2
  const { stringifyValue } = require('../utils/normalizeUtils');
3
- const { fhirId } = require('../helpers/fhirHelper');
3
+ const { fhirId, codeSystemUrl } = require('../helpers/fhirHelper');
4
+ const { ctcaeSlug } = require('../helpers/terminologyHelper');
4
5
  const { reference, patientReference, codeableConcept, extension, toInstant } = require('../helpers/elementHelper');
5
6
  const { baseResource, problemListCategory, observationCategory } = require('../helpers/resourceHelper');
6
7
  const { MENTION_SLUG } = require('../constants/projectionSlugs');
@@ -48,7 +49,7 @@ function primaryResource(mention) {
48
49
 
49
50
  function mentionCode(fact) {
50
51
  return fact.ctcaeTerm
51
- ? codeableConcept(fact.canonicalTerm, { code: fact.ctcaeTerm, system: getSystems().ctcae, display: fact.ctcaeTerm })
52
+ ? codeableConcept(fact.canonicalTerm, { code: ctcaeSlug(fact.ctcaeTerm), system: codeSystemUrl('ctcae-v5-term'), display: fact.ctcaeTerm })
52
53
  : codeableConcept(fact.canonicalTerm);
53
54
  }
54
55
 
@@ -14,6 +14,9 @@ const COMPOSE_AS_PREFIX = 'compose_as: ';
14
14
 
15
15
  const ccText = (concept) => concept?.text || null;
16
16
  const caseReason = (caseId) => [{ reference: reference('Condition', caseId) }];
17
+ // Older rows hold a flat Reference; R5 types finding.item as CodeableReference.
18
+ const findingItemReference = (item) =>
19
+ (typeof item?.reference === 'string' ? item.reference : item?.reference?.reference);
17
20
 
18
21
  function dispositionBase(resourceType, disposition) {
19
22
  return baseResource(resourceType, disposition.dispositionId, ROUTING_DISPOSITION_SLUG, disposition.patientId);
@@ -141,7 +144,7 @@ function assessmentResource(assessment, { decisionId, committedAt, disposition }
141
144
  const entry = {};
142
145
  const extensions = [];
143
146
  if (finding.caseId) {
144
- entry.item = reference('Condition', finding.caseId);
147
+ entry.item = { reference: reference('Condition', finding.caseId) };
145
148
  extensions.push(extension(ROUTING_EXT.FINDING_CASE_ID, { valueString: finding.caseId }));
146
149
  }
147
150
  extensions.push(
@@ -244,7 +247,7 @@ function reconstructAssessment(resource, patientId, turnId) {
244
247
  findings: (resource.finding || []).map((finding) => {
245
248
  const findingExt = extMap(finding);
246
249
  return {
247
- caseId: referencedId(finding, ROUTING_EXT.FINDING_CASE_ID, finding.item?.reference),
250
+ caseId: referencedId(finding, ROUTING_EXT.FINDING_CASE_ID, findingItemReference(finding.item)),
248
251
  clinicalReasoning: findingExt[ROUTING_EXT.FINDING_REASONING] || '',
249
252
  decisionAction: findingExt[ROUTING_EXT.FINDING_ACTION] || '',
250
253
  };
@@ -261,12 +264,12 @@ function reconstructDisposition(resource, assessment, patientId) {
261
264
  patientId,
262
265
  kind,
263
266
  primaryAction: codec.actionOf(resource),
264
- primaryReason: codec.reasonOf(resource),
267
+ primaryReason: codec.reasonOf(resource) || '',
265
268
  primaryCaseId: extMap(assessment)[ROUTING_EXT.PRIMARY_CASE_ID] || null,
266
269
  secondaryActions: (resource.action || []).slice(1).map((action) => {
267
270
  const description = action.description || '';
268
271
  return {
269
- action: action.title,
272
+ action: action.title || '',
270
273
  composeAs: description.startsWith(COMPOSE_AS_PREFIX) ? description.slice(COMPOSE_AS_PREFIX.length) : description,
271
274
  };
272
275
  }),
@@ -13,6 +13,7 @@ const {
13
13
  ESCALATION_CASE_SLUG,
14
14
  ESCALATION_CASE_STATUS_SLUG,
15
15
  ESCALATION_DECISION_SLUG,
16
+ SYMPTOM_CASE_SLUG,
16
17
  } = require('../constants/projectionSlugs');
17
18
  const { SEVERITY_TO_PRIORITY } = require('../constants/severityPriority');
18
19
  const { caseStatusOf } = require('../constants/escalationCaseStatus');
@@ -74,7 +75,12 @@ class Task {
74
75
  requester: reference('Device', deviceId),
75
76
  executionPeriod: { start: toIso(review.createdAt), ...(review.closedAt ? { end: toIso(review.closedAt) } : {}) },
76
77
  };
77
- if (conditionIds.length) payload.reason = conditionIds.map((id) => ({ reference: reference('Condition', id) }));
78
+ if (conditionIds.length) {
79
+ payload.reason = conditionIds.map((id) => {
80
+ const symptom = { ...reference('Condition', id), type: 'Condition', identifier: identifier(SYMPTOM_CASE_SLUG, id) };
81
+ return { reference: symptom };
82
+ });
83
+ }
78
84
  // Only a code reaches FHIR: the operator's cancellation note is free text.
79
85
  if (review.status === 'cancelled') {
80
86
  const reasonCode = String(review.cancellationReason ?? '').startsWith('no_requiere') ? 'no_requiere' : 'cancelado_por_equipo';
@@ -1,6 +1,7 @@
1
1
  const { getDeviceId } = require('../config/fhirConfig');
2
2
  const { fhirId } = require('../helpers/fhirHelper');
3
- const { ESCALATION_SLUG } = require('../constants/projectionSlugs');
3
+ const { identifierValue } = require('../helpers/fhirReadHelper');
4
+ const { ESCALATION_SLUG, ESCALATION_CASE_SLUG } = require('../constants/projectionSlugs');
4
5
  const { getFhirStore } = require('../stores/fhirStore');
5
6
  const { fromFhir } = require('../projections/dispatchedEscalationProjection');
6
7
  const { Task } = require('../resources/Task');
@@ -43,7 +44,42 @@ async function storeEscalationCase({ review, priority, conditionIds }) {
43
44
  return { ids: stored };
44
45
  }
45
46
 
47
+ const CLOSED_CASE_STATUSES = ['completed', 'cancelled'];
48
+
49
+ function caseFromTask(task) {
50
+ return {
51
+ reviewId: identifierValue(task, ESCALATION_CASE_SLUG),
52
+ status: task.status,
53
+ businessStatus: task.businessStatus?.coding?.[0]?.code ?? null,
54
+ label: task.businessStatus?.text ?? null,
55
+ isOpen: !CLOSED_CASE_STATUSES.includes(task.status),
56
+ priority: task.priority ?? null,
57
+ // Only references that carry the original symptom case id; a Task written before they did reads as none.
58
+ conditionIds: (task.reason ?? []).map((reason) => reason.reference?.identifier?.value).filter(Boolean),
59
+ decision: task.output?.find((output) => output.type?.text === 'decision')?.valueCodeableConcept?.coding?.[0]?.code ?? null,
60
+ statusReason: task.statusReason?.concept?.text ?? null,
61
+ openedAt: task.authoredOn ?? null,
62
+ lastModified: task.lastModified ?? null,
63
+ closedAt: task.executionPeriod?.end ?? null,
64
+ };
65
+ }
66
+
67
+ // A patient's escalation cases, newest first; `openOnly` keeps the ones whose Task is not completed or cancelled.
68
+ async function readEscalationCases({ patientId, openOnly = false }) {
69
+ if (typeof patientId !== 'string' || !patientId.trim()) {
70
+ throw new Error('readEscalationCases requires a non-empty patientId');
71
+ }
72
+ const found = await getFhirStore().find({
73
+ patient: `Patient/${fhirId(patientId)}`,
74
+ resourceType: 'Task',
75
+ identifierSlug: ESCALATION_CASE_SLUG,
76
+ });
77
+ const cases = found.map(caseFromTask);
78
+ return openOnly ? cases.filter((escalationCase) => escalationCase.isOpen) : cases;
79
+ }
80
+
46
81
  module.exports = {
47
82
  readDispatchedEscalations,
83
+ readEscalationCases,
48
84
  storeEscalationCase,
49
85
  };
@@ -30,10 +30,16 @@ 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.
33
+ // A plan rewrite reprojects its Tasks as freshly `requested` with no `output`, where the outcomes and
34
+ // verdicts live; an outcome also moved the status, so both survive the rewrite.
34
35
  const keepTaskOutput = {
35
36
  merge: (prior, incoming) => (prior.resourceType === 'Task' && prior.output?.length
36
- ? { ...incoming, output: prior.output }
37
+ ? {
38
+ ...incoming,
39
+ output: prior.output,
40
+ status: prior.status || incoming.status,
41
+ ...(prior.lastModified ? { lastModified: prior.lastModified } : {}),
42
+ }
37
43
  : incoming),
38
44
  };
39
45
 
@@ -33,6 +33,10 @@ const { safetyGateExists } = require('./riskService');
33
33
  const { getCatalog } = require('./terminologyService');
34
34
 
35
35
  const OUTCOME_VALUES = ['improved', 'partial', 'no_relief', 'worsened', 'not_tried', 'unknown'];
36
+ // The patient tried it: the recommendation is done. not_tried / unknown leave it open. With no outcome (every
37
+ // triage record, and adherence-only chat records), adherence full/partial ("la siguió", "en parte") means it was tried.
38
+ const TRIED_OUTCOMES = new Set(['improved', 'partial', 'no_relief', 'worsened']);
39
+ const TRIED_ADHERENCE = new Set(['full', 'partial']);
36
40
  const ADHERENCE_VALUES = ['full', 'partial', 'none'];
37
41
  const CHAT_ACTIVE_WINDOW_MS = 7 * 24 * 60 * 60 * 1000;
38
42
  const SOURCE_VALUES = ['chat', 'triage'];
@@ -162,12 +166,22 @@ async function recordRecommendationOutcome({
162
166
  }
163
167
  const target = await resolveTask({ patientId, recommendationId, ctcaeTerm });
164
168
  if (!target) return { recorded: false };
165
- const output = outcomeEntry({ outcome: resolvedOutcome, adherence, notes, source, recordedAt: toIso(new Date()), eventKey });
169
+ const recordedAt = toIso(new Date());
170
+ const output = outcomeEntry({ outcome: resolvedOutcome, adherence, notes, source, recordedAt, eventKey });
166
171
  let duplicate = false;
167
172
  await storeResources([target.task], {
168
- merge: (prior, incoming) => {
173
+ merge: (prior) => {
169
174
  duplicate = Boolean(eventKey) && hasOutcomeEvent(prior, eventKey);
170
- return { ...incoming, output: duplicate ? prior.output : [...(prior.output || []), output] };
175
+ if (duplicate) return prior;
176
+ const done = prior.status === 'completed'
177
+ || TRIED_OUTCOMES.has(resolvedOutcome)
178
+ || (!outcome && TRIED_ADHERENCE.has(adherence));
179
+ return {
180
+ ...prior,
181
+ status: done ? 'completed' : 'in-progress',
182
+ lastModified: recordedAt,
183
+ output: [...(prior.output || []), output],
184
+ };
171
185
  },
172
186
  });
173
187
  return {
@@ -224,13 +238,13 @@ async function recordRecommendationReview({
224
238
  let duplicate = false;
225
239
  let retained = null;
226
240
  const write = await storeResources([target.task], {
227
- merge: (prior, incoming) => {
241
+ merge: (prior) => {
228
242
  duplicate = Boolean(key) && hasReviewEvent(prior, key);
229
243
  if (duplicate) {
230
244
  retained = reviewByEvent(prior, key);
231
- return { ...incoming, output: prior.output };
245
+ return prior;
232
246
  }
233
- return { ...incoming, output: [...(prior.output || []), output] };
247
+ return { ...prior, output: [...(prior.output || []), output] };
234
248
  },
235
249
  });
236
250
  if (write.skipped) return { recorded: false, skipped: write.skipped, recommendation_id: target.recommendationId };
@@ -182,7 +182,7 @@ function reconstructDisease(prediction) {
182
182
  function reconstructComorbidity(prediction) {
183
183
  return {
184
184
  comorbidity: outcomeText(prediction),
185
- interaction: prediction.rationale,
185
+ interaction: prediction.rationale ?? '',
186
186
  clinicalNote: extValues(prediction, RISK_EXT.COMORBIDITY_CLINICAL_NOTE)[0] || null,
187
187
  };
188
188
  }
@@ -1,5 +1,6 @@
1
+ const { codeableConcept } = require('../helpers/elementHelper');
1
2
  const { fhirId } = require('../helpers/fhirHelper');
2
- const { ROUTING_ASSESSMENT_SLUG } = require('../constants/projectionSlugs');
3
+ const { ROUTING_ASSESSMENT_SLUG, ROUTING_DISPOSITION_SLUG } = require('../constants/projectionSlugs');
3
4
  const { getFhirStore } = require('../stores/fhirStore');
4
5
  const { toFhir, fromFhir } = require('../projections/routingProjection');
5
6
  const { storeResources } = require('./fhirService');
@@ -12,6 +13,54 @@ async function storeRoutingDecision({ patientId, routingDecision }) {
12
13
  return { count: stored.length, ids: stored };
13
14
  }
14
15
 
16
+ const DISPOSITION_TYPES = ['Task', 'CommunicationRequest', 'RequestOrchestration', 'CarePlan'];
17
+ const OPEN_STATUSES = new Set(['draft', 'requested', 'received', 'accepted', 'ready', 'in-progress', 'on-hold', 'active']);
18
+ // Handing a case to the team carries these actions out; the bot's own follow-ups are withdrawn instead.
19
+ const ESCALATION_ACTIONS = new Set(['team_escalation', 'emergency_escalation', 'palliative_referral']);
20
+
21
+ const caseLinks = (resource) => [...(resource.reason || []), ...(resource.addresses || [])]
22
+ .map((link) => link.reference?.reference)
23
+ .filter(Boolean);
24
+ const primaryActionOf = (resource) => resource.code?.text || resource.action?.[0]?.title || null;
25
+
26
+ function closedStatus(resource, { closeReason, resolving }) {
27
+ if (resolving) return 'completed';
28
+ const done = closeReason === 'escalated_to_team' && ESCALATION_ACTIONS.has(primaryActionOf(resource));
29
+ if (resource.resourceType === 'Task') return done ? 'completed' : 'cancelled';
30
+ return done ? 'completed' : 'revoked';
31
+ }
32
+
33
+ function closedFields(resource, { closeReason, resolving }, now) {
34
+ const fields = { status: closedStatus(resource, { closeReason, resolving }) };
35
+ if (resource.resourceType === 'Task') {
36
+ fields.statusReason = { concept: codeableConcept(closeReason) };
37
+ fields.lastModified = now;
38
+ }
39
+ if (resource.resourceType === 'CommunicationRequest') fields.statusReason = codeableConcept(closeReason);
40
+ return fields;
41
+ }
42
+
43
+ async function closeRoutingDispositions({ patientId, caseId, closeReason, resolving }) {
44
+ if (!closeReason) throw new Error('closeRoutingDispositions requires the case closeReason');
45
+ const store = getFhirStore();
46
+ const caseRef = `Condition/${fhirId(caseId)}`;
47
+ const dispositions = await store.find({
48
+ patient: `Patient/${fhirId(patientId)}`,
49
+ resourceType: DISPOSITION_TYPES,
50
+ identifierSlug: ROUTING_DISPOSITION_SLUG,
51
+ });
52
+ const open = dispositions.filter((resource) => OPEN_STATUSES.has(resource.status) && caseLinks(resource).includes(caseRef));
53
+ const now = new Date().toISOString();
54
+ const closed = [];
55
+ for (const resource of open) {
56
+ const { stored } = await storeResources([resource], {
57
+ merge: (prior) => (OPEN_STATUSES.has(prior.status) ? { ...prior, ...closedFields(prior, { closeReason, resolving }, now) } : prior),
58
+ });
59
+ closed.push(...stored);
60
+ }
61
+ return { closed };
62
+ }
63
+
15
64
  async function readRoutingDecisions({ patientId, turnId = null }) {
16
65
  const store = getFhirStore();
17
66
  const patient = `Patient/${fhirId(patientId)}`;
@@ -31,6 +80,7 @@ async function readRoutingDecisions({ patientId, turnId = null }) {
31
80
  }
32
81
 
33
82
  module.exports = {
83
+ closeRoutingDispositions,
34
84
  storeRoutingDecision,
35
85
  readRoutingDecisions,
36
86
  };
@@ -6,6 +6,7 @@ const { getCatalog } = require('../config/catalogConfig');
6
6
  const { envelopeSchema } = require('../models/envelopeModel');
7
7
  const { historySchema } = require('../models/historyModel');
8
8
 
9
+ const { pruneEmptyElements } = require('../helpers/elementHelper');
9
10
  const { identifierSystem } = require('../helpers/fhirHelper');
10
11
 
11
12
  const FHIR_VIEW = 'fhirResourceView';
@@ -131,7 +132,7 @@ class FhirStore {
131
132
  }
132
133
 
133
134
  _toStoredResource(resource) {
134
- return JSON.parse(JSON.stringify(resource));
135
+ return pruneEmptyElements(JSON.parse(JSON.stringify(resource)));
135
136
  }
136
137
 
137
138
  _entryFor(resourceType) {
@@ -216,6 +216,7 @@ const escalationReviewSchema = new mongoose.Schema({
216
216
  closedBy: { type: String, default: null },
217
217
  closedAt: { type: Date, default: null },
218
218
  cancellationReason: { type: String, default: null },
219
+ caseStatusMirror: { type: mongoose.Schema.Types.Mixed, default: null },
219
220
  }, { timestamps: true });
220
221
 
221
222
  // The fields the FHIR case Task is built from; a write that touches one tells the listeners.
@@ -251,6 +252,20 @@ escalationReviewSchema.index({ draftDueAt: 1 }, { partialFilterExpression: { dra
251
252
  escalationReviewSchema.index({ doctorAlertDueAt: 1 }, { partialFilterExpression: { doctorAlertDueAt: { $type: 'date' } } });
252
253
  escalationReviewSchema.index({ patientCode: 1 }, { unique: true, partialFilterExpression: { closedAt: null } });
253
254
 
255
+ const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
256
+ ? review.patientCaseRecordIds
257
+ : (review.patientCaseRecordId ? [review.patientCaseRecordId] : []));
258
+
259
+ // A closed review leaves the cases the patient's open review now holds to that review.
260
+ async function supersededCaseIds(EscalationReview, review) {
261
+ if (!review.closedAt) return new Set();
262
+ const owner = await EscalationReview
263
+ .findOne({ patientCode: review.patientCode, closedAt: null }, { patientCaseRecordIds: 1, patientCaseRecordId: 1 })
264
+ .lean();
265
+ if (!owner || String(owner._id) === String(review._id)) return new Set();
266
+ return new Set(caseIdsOf(owner));
267
+ }
268
+
254
269
  const getEscalationReview = () => {
255
270
  const dbName = getModelDatabase('EscalationReview');
256
271
  const db = dbName ? getDb(dbName) : mongoose;
@@ -275,4 +290,6 @@ module.exports = {
275
290
  notifyCaseWrite,
276
291
  onCaseWrite,
277
292
  touchesCase,
293
+ caseIdsOf,
294
+ supersededCaseIds,
278
295
  };
@@ -1,8 +1,14 @@
1
1
  const runtimeConfig = require('../config/runtimeConfig');
2
2
  const { logger } = require('../utils/logger');
3
- const { getEscalationReview, onCaseWrite } = require('../models/escalationReviewModel');
3
+ const { isShadowRun } = require('../utils/shadowScope');
4
+ const { caseIdsOf, getEscalationReview, onCaseWrite, supersededCaseIds } = require('../models/escalationReviewModel');
4
5
  const { storeEscalationCase } = require('../fhir/services/escalationService');
6
+ const { caseStatusOf } = require('../fhir/constants/escalationCaseStatus');
5
7
  const { effectiveUrgencyOf } = require('./reviewDeadlineService');
8
+ const { updatePatientTask } = require('./patientTaskService');
9
+
10
+ const MIRROR_OPERATOR = 'bot:escalationCase';
11
+ const MIRROR_SOURCE = 'escalation_case';
6
12
 
7
13
  const caseTaskLive = () => String(runtimeConfig.get('ESCALATION_CASE_TASK_LIVE', 'false')).trim().toLowerCase() === 'true';
8
14
 
@@ -11,17 +17,53 @@ function conditionIdsOf(review) {
11
17
  return [...new Set([...(review.followUpCases ?? []), ...impressed].filter((id) => typeof id === 'string' && id))];
12
18
  }
13
19
 
20
+ // The linked Airtable cases show the stored Task's status in status_operaciones; only a change is written.
21
+ async function mirrorToCases(review) {
22
+ const { businessStatus, label } = caseStatusOf(review.status);
23
+ const superseded = await supersededCaseIds(getEscalationReview(), review);
24
+ const recordIds = caseIdsOf(review).filter((recordId) => !superseded.has(recordId));
25
+ const mirrored = review.caseStatusMirror;
26
+ const pending = recordIds.filter((recordId) => mirrored?.businessStatus !== businessStatus || !mirrored.recordIds?.includes(recordId));
27
+ if (!pending.length) return;
28
+ const settled = [];
29
+ for (const recordId of pending) {
30
+ try {
31
+ await updatePatientTask({
32
+ code: review.patientCode, kind: 'cases', recordId, changes: { operationsStatus: label }, updatedBy: MIRROR_OPERATOR, source: MIRROR_SOURCE,
33
+ });
34
+ settled.push(recordId);
35
+ } catch (error) {
36
+ // A case of another patient or program is never written; it is settled rather than retried on every sync.
37
+ if (error?.statusCode === 404) {
38
+ logger.warn('[EscalationCaseTask] The linked case is not this patient\'s program case; it is left as is', { escalationReviewId: String(review._id), recordId });
39
+ settled.push(recordId);
40
+ } else {
41
+ logger.error('[EscalationCaseTask] The case status did not reach the Airtable case', { escalationReviewId: String(review._id), recordId, error: error.message });
42
+ }
43
+ }
44
+ }
45
+ if (!settled.length) return;
46
+ const kept = mirrored?.businessStatus === businessStatus ? mirrored.recordIds ?? [] : [];
47
+ await getEscalationReview().updateOne(
48
+ { _id: review._id },
49
+ { $set: { caseStatusMirror: { businessStatus, recordIds: [...new Set([...kept, ...settled])] } } },
50
+ { timestamps: false },
51
+ );
52
+ }
53
+
14
54
  async function syncCaseTask(id) {
15
55
  const review = await getEscalationReview().findById(id).lean();
16
56
  if (!review) return null;
17
- return storeEscalationCase({ review, priority: effectiveUrgencyOf(review)?.urgency ?? null, conditionIds: conditionIdsOf(review) });
57
+ const stored = await storeEscalationCase({ review, priority: effectiveUrgencyOf(review)?.urgency ?? null, conditionIds: conditionIdsOf(review) });
58
+ await mirrorToCases(review);
59
+ return stored;
18
60
  }
19
61
 
20
62
  // Syncs of one review run one after another, each reading the review fresh, so the last write carries the last state.
21
63
  const inFlight = new Map();
22
64
 
23
65
  function scheduleCaseSync(id) {
24
- if (!caseTaskLive()) return null;
66
+ if (!caseTaskLive() || isShadowRun()) return null;
25
67
  const next = (inFlight.get(id) ?? Promise.resolve())
26
68
  .then(() => syncCaseTask(id))
27
69
  .catch((error) => logger.error('[EscalationCaseTask] The FHIR case was not synced', { escalationReviewId: id, error: error.message }));
@@ -32,4 +74,4 @@ function scheduleCaseSync(id) {
32
74
 
33
75
  onCaseWrite(scheduleCaseSync);
34
76
 
35
- module.exports = { conditionIdsOf, scheduleCaseSync, syncCaseTask };
77
+ module.exports = { caseTaskLive, conditionIdsOf, scheduleCaseSync, syncCaseTask };
@@ -18,7 +18,9 @@ const {
18
18
  RETURN_REASONS,
19
19
  URGENCY_LEVELS,
20
20
  URGENCY_RANK,
21
+ caseIdsOf,
21
22
  getEscalationReview,
23
+ supersededCaseIds,
22
24
  } = require('../models/escalationReviewModel');
23
25
  const { getPatientAuditLog } = require('../models/patientAuditLogModel');
24
26
  const { isWithin24HourWindow } = require('../helpers/conversationWindowHelper');
@@ -48,7 +50,7 @@ const { countMessages } = require('./messageService');
48
50
  const { getEscalationApprover, listEscalationApprovers } = require('./physicianService');
49
51
  const { getThreadInfo, switchThreadStoppedStatus } = require('./threadService');
50
52
  const { effectiveUrgencyOf, responseDeadlineOf, responseDeadlinePolicy } = require('./reviewDeadlineService');
51
- require('./escalationCaseTaskService');
53
+ const { caseTaskLive } = require('./escalationCaseTaskService');
52
54
 
53
55
  const getMessaging = () => require('../core/NexusMessaging');
54
56
 
@@ -125,10 +127,6 @@ const configured = (key) => {
125
127
  const STATUS_AFTER = { edited_approved: 'approved', monitor: 'monitoring' };
126
128
  const statusAfter = (decision) => STATUS_AFTER[decision] ?? decision;
127
129
 
128
- const caseIdsOf = (review) => (Array.isArray(review.patientCaseRecordIds)
129
- ? review.patientCaseRecordIds
130
- : (review.patientCaseRecordId ? [review.patientCaseRecordId] : []));
131
-
132
130
  const redactedError = (error) => redactDirectIdentifiers(String(error?.message || ''));
133
131
 
134
132
  const redactedStack = (error) => redactDirectIdentifiers(String(error?.stack || ''));
@@ -223,15 +221,6 @@ async function completeOperation(id, claim, fromStatus, recordUpdate, nextStatus
223
221
  throw httpError(409, STATUS_CONFLICT);
224
222
  }
225
223
 
226
- async function supersededCaseIds(EscalationReview, review) {
227
- if (!review.closedAt) return new Set();
228
- const owner = await EscalationReview
229
- .findOne({ patientCode: review.patientCode, closedAt: null }, { patientCaseRecordIds: 1, patientCaseRecordId: 1 })
230
- .lean();
231
- if (!owner || String(owner._id) === String(review._id)) return new Set();
232
- return new Set(caseIdsOf(owner));
233
- }
234
-
235
224
  const summarise = (outcomes) => {
236
225
  if (!outcomes.length) return 'skipped';
237
226
  if (outcomes.every((outcome) => outcome.status === 'superseded')) return 'superseded';
@@ -1634,7 +1623,8 @@ async function handOffToDoctor({ id, mode, physicianEmail = null, sentBy, reques
1634
1623
  $addToSet: { patientCaseRecordIds: { $each: patientCaseRecordIds } },
1635
1624
  $unset: { identityBlock: '' },
1636
1625
  };
1637
- const recordUpdate = withCaseMirror({ ...review, patientCaseRecordIds }, handoff, { status: 'en revision_medica' });
1626
+ // With the case Task live, the case's operations status comes from the Task; the clinical status stays clinical.
1627
+ const recordUpdate = caseTaskLive() ? handoff : withCaseMirror({ ...review, patientCaseRecordIds }, handoff, { status: 'en revision_medica' });
1638
1628
  updated = await completeOperation(reviewId, claim, 'handing_off', recordUpdate, 'awaiting_doctor', handoff);
1639
1629
  } catch (error) {
1640
1630
  await releaseReview(reviewId, 'handing_off', review.status, claim);
@@ -18,6 +18,7 @@ const {
18
18
  const { getRecordByFilter, updateRecordByFilter } = require('../services/airtableService');
19
19
  const { logPatientChange } = require('../services/patientService');
20
20
  const { clearOpenTaskSummary } = require('../services/patientTaskSummaryService');
21
+ const { CASE_STATUS_BY_REVIEW_STATUS } = require('../fhir/constants/escalationCaseStatus');
21
22
 
22
23
  const MAX_ROWS = 50;
23
24
  const MAX_NOTE_LENGTH = 5000;
@@ -58,15 +59,8 @@ const CASE_STATUSES = [
58
59
  'radioterapia_revisión',
59
60
  'internado',
60
61
  ];
61
- const OPERATIONS_STATUSES = [
62
- 'cerrado',
63
- 'coordinación médica',
64
- 'síntoma marcado',
65
- 'pendiente',
66
- 'notificado ops',
67
- 'notificado medical',
68
- 'sin caracterizar',
69
- ];
62
+ // The operations status of a case is its FHIR case Task status, the same vocabulary nexus mirrors.
63
+ const OPERATIONS_STATUSES = [...new Set(Object.values(CASE_STATUS_BY_REVIEW_STATUS).map(({ label }) => label))];
70
64
 
71
65
  const toRow = (record) => ({ _recordId: record.id, _createdTime: record._rawJson?.createdTime, ...record.fields });
72
66
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@peopl-health/nexus",
3
- "version": "5.72.0-dev.13744",
3
+ "version": "5.72.0-dev.14094",
4
4
  "description": "Core messaging and assistant library for WhatsApp communication platforms",
5
5
  "keywords": [
6
6
  "whatsapp",