@precisa-saude/fhir 0.33.0 → 0.34.0
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.
- package/README.md +2 -0
- package/dist/{chunk-ZCIZUBMR.cjs → chunk-376KM7IL.cjs} +10 -3
- package/dist/chunk-376KM7IL.cjs.map +1 -0
- package/dist/{chunk-KS2YZBAS.js → chunk-K3VZ3F5Z.js} +8 -2
- package/dist/chunk-K3VZ3F5Z.js.map +1 -0
- package/dist/{chunk-X5WVIJGG.js → chunk-NJM45WAH.js} +8 -1
- package/dist/chunk-NJM45WAH.js.map +1 -0
- package/dist/{chunk-FGZXQWSR.cjs → chunk-NKDUVSDK.cjs} +8 -2
- package/dist/chunk-NKDUVSDK.cjs.map +1 -0
- package/dist/{chunk-WXCX5TJJ.js → chunk-P4G534AQ.js} +444 -60
- package/dist/chunk-P4G534AQ.js.map +1 -0
- package/dist/{chunk-LXKFVJF4.cjs → chunk-VKLWTTUO.cjs} +445 -61
- package/dist/chunk-VKLWTTUO.cjs.map +1 -0
- package/dist/cli.js +1237 -847
- package/dist/{converter-DZH9x52r.d.cts → converter-DP8VkkO3.d.cts} +9 -1
- package/dist/{converter-D1Q84Oc9.d.ts → converter-UygMzWlL.d.ts} +9 -1
- package/dist/converter.cjs +3 -2
- package/dist/converter.cjs.map +1 -1
- package/dist/converter.d.cts +3 -2
- package/dist/converter.d.ts +3 -2
- package/dist/converter.js +2 -1
- package/dist/{fhir-types-B1KQmlRb.d.ts → fhir-types-Cn5WFbOI.d.cts} +5 -0
- package/dist/{fhir-types-B1KQmlRb.d.cts → fhir-types-Cn5WFbOI.d.ts} +5 -0
- package/dist/importer.cjs +2 -2
- package/dist/importer.d.cts +3 -1
- package/dist/importer.d.ts +3 -1
- package/dist/importer.js +1 -1
- package/dist/index.cjs +11 -7
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +5 -5
- package/dist/index.d.ts +5 -5
- package/dist/index.js +8 -4
- package/dist/index.js.map +1 -1
- package/dist/reference-ranges.cjs +6 -2
- package/dist/reference-ranges.cjs.map +1 -1
- package/dist/reference-ranges.d.cts +83 -1
- package/dist/reference-ranges.d.ts +83 -1
- package/dist/reference-ranges.js +7 -3
- package/dist/validators.d.cts +1 -1
- package/dist/validators.d.ts +1 -1
- package/package.json +1 -1
- package/dist/chunk-FGZXQWSR.cjs.map +0 -1
- package/dist/chunk-KS2YZBAS.js.map +0 -1
- package/dist/chunk-LXKFVJF4.cjs.map +0 -1
- package/dist/chunk-WXCX5TJJ.js.map +0 -1
- package/dist/chunk-X5WVIJGG.js.map +0 -1
- package/dist/chunk-ZCIZUBMR.cjs.map +0 -1
package/README.md
CHANGED
|
@@ -107,6 +107,8 @@ const range = getReferenceRange('TSH', {
|
|
|
107
107
|
// → { max: 2.5, min: 0.1, ... } (alvo ATA 2017 para 1º trimestre)
|
|
108
108
|
```
|
|
109
109
|
|
|
110
|
+
Cada faixa diz que tipo de afirmação ela é (`kind`: intervalo de referência do ensaio, limiar de decisão de diretriz ou distribuição populacional) e, por limite, se ele é corte clínico ou só desenho (`minKind`/`maxKind`). Para sinalizar um valor contra a faixa do catálogo, use `flagAgainstCatalogRange`, que ignora os limites de desenho; o `direction` diz para que lado o marcador melhora e não decide flag. Detalhes em [docs/biomarcadores.md](../../docs/biomarcadores.md#tipo-da-faixa).
|
|
111
|
+
|
|
110
112
|
O metadado opcional `fastingRequired` em `BiomarkerReferenceRange` indica se a amostra exige jejum estrito (ex.: `Glucose`, `Insulin`, `HOMA_IR`) ou se o jejum é preferido mas não obrigatório (ex.: `Triglycerides`, que aceita dosagem não-jejum por SBC 2017/2025).
|
|
111
113
|
|
|
112
114
|
## Aviso médico
|
|
@@ -107,20 +107,27 @@ function mapFHIRObservationToInternal(observation, index) {
|
|
|
107
107
|
}
|
|
108
108
|
let referenceMin;
|
|
109
109
|
let referenceMax;
|
|
110
|
+
let referenceKind;
|
|
110
111
|
if (_optionalChain([observation, 'access', _18 => _18.referenceRange, 'optionalAccess', _19 => _19[0]])) {
|
|
111
112
|
referenceMin = _optionalChain([observation, 'access', _20 => _20.referenceRange, 'access', _21 => _21[0], 'access', _22 => _22.low, 'optionalAccess', _23 => _23.value]);
|
|
112
113
|
referenceMax = _optionalChain([observation, 'access', _24 => _24.referenceRange, 'access', _25 => _25[0], 'access', _26 => _26.high, 'optionalAccess', _27 => _27.value]);
|
|
114
|
+
const meaning = _optionalChain([observation, 'access', _28 => _28.referenceRange, 'access', _29 => _29[0], 'access', _30 => _30.type, 'optionalAccess', _31 => _31.coding, 'optionalAccess', _32 => _32.find, 'call', _33 => _33(
|
|
115
|
+
(c) => c.system === "http://terminology.hl7.org/CodeSystem/referencerange-meaning"
|
|
116
|
+
), 'optionalAccess', _34 => _34.code]);
|
|
117
|
+
if (meaning === "normal") referenceKind = "reference-interval";
|
|
118
|
+
else if (meaning === "recommended") referenceKind = "decision-threshold";
|
|
113
119
|
}
|
|
114
120
|
const imported = {
|
|
115
121
|
biomarkerCode: internalCode,
|
|
116
|
-
biomarkerName: _optionalChain([definition, 'optionalAccess',
|
|
122
|
+
biomarkerName: _optionalChain([definition, 'optionalAccess', _35 => _35.names, 'access', _36 => _36.pt, 'access', _37 => _37[0]]) || _optionalChain([definition, 'optionalAccess', _38 => _38.names, 'access', _39 => _39.en, 'access', _40 => _40[0]]) || observation.code.text || internalCode,
|
|
117
123
|
collectionDate,
|
|
118
124
|
flag: extractFlag(observation),
|
|
119
125
|
isQualitative,
|
|
120
126
|
loincCode,
|
|
127
|
+
...referenceKind && { referenceKind },
|
|
121
128
|
referenceMax,
|
|
122
129
|
referenceMin,
|
|
123
|
-
unit: unit || _optionalChain([definition, 'optionalAccess',
|
|
130
|
+
unit: unit || _optionalChain([definition, 'optionalAccess', _41 => _41.unit]) || "",
|
|
124
131
|
value
|
|
125
132
|
};
|
|
126
133
|
return { observation: imported };
|
|
@@ -162,4 +169,4 @@ function processImportBundle(data) {
|
|
|
162
169
|
|
|
163
170
|
|
|
164
171
|
exports.MAX_OBSERVATIONS = MAX_OBSERVATIONS; exports.MAX_FILE_SIZE = MAX_FILE_SIZE; exports.extractObservationsFromBundle = extractObservationsFromBundle; exports.mapFHIRObservationToInternal = mapFHIRObservationToInternal; exports.processImportBundle = processImportBundle;
|
|
165
|
-
//# sourceMappingURL=chunk-
|
|
172
|
+
//# sourceMappingURL=chunk-376KM7IL.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-376KM7IL.cjs","../src/importer.ts"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACkDA,IAAM,iBAAA,EAAmB,GAAA;AACzB,IAAM,cAAA,EAAgB,GAAA,EAAK,KAAA,EAAO,IAAA;AAclC,SAAS,oBAAA,CAAqB,WAAA,EAI5B;AACA,EAAA,MAAM,OAAA,mCAAS,WAAA,mBAAY,IAAA,6BAAM,QAAA,UAAU,CAAC,GAAA;AAC5C,EAAA,MAAM,UAAA,kBAAY,MAAA,qBAAO,IAAA,mBAAK,CAAC,CAAA,EAAA,GAAM,CAAA,CAAE,OAAA,IAAW,8BAAY,CAAA,6BAAG,MAAA;AACjE,EAAA,MAAM,aAAA,kBAAe,MAAA,qBAAO,IAAA,mBAAK,CAAC,CAAA,EAAA,GAAM,CAAA,CAAE,OAAA,IAAW,uCAAqB,CAAA,6BAAG,MAAA;AAE7E,EAAA,MAAM,UAAA,EAAY;AAAA,IAChB,GAAI,UAAA,EAAY,CAAC,CAAA,MAAA,EAAS,SAAS,CAAA,CAAA;AACf,IAAA;AACtB,EAAA;AAOI,EAAA;AACsB,EAAA;AACE,IAAA;AACE,EAAA;AACO,IAAA;AAC1B,IAAA;AACJ,EAAA;AACI,IAAA;AACX,EAAA;AAE8B,EAAA;AACN,EAAA;AAEQ,EAAA;AA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EAAA;AAEb,EAAA;AAChB,IAAA;AAEc,IAAA;AACK,MAAA;AAC3B,IAAA;AACyB,MAAA;AAChC,IAAA;AACF,EAAA;AAEO,EAAA;AACI,IAAA;AACT,IAAA;AACS,IAAA;AACoB,IAAA;AAC/B,EAAA;AACF;ADrIuC;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-376KM7IL.cjs","sourcesContent":[null,"/**\n * FHIR Importer\n *\n * Parses FHIR R4 Bundles and extracts Observation resources with known LOINC codes,\n * mapping them to internal biomarker codes for storage as lab results.\n */\n\nimport {\n codeToLoinc,\n getDefinitionByCode,\n isValidCode,\n loincToCode,\n normalizeCode,\n} from './biomarkers';\nimport { BIOMARKER_CODE_SYSTEM, LOINC_SYSTEM } from './code-systems';\nimport type { FHIRBundle, FHIRObservation } from './fhir-types';\nimport { validateFHIRImportBundle } from './validators';\n\nexport interface ImportedObservation {\n biomarkerCode: string;\n biomarkerName: string;\n collectionDate: string;\n flag: 'H' | 'L' | '';\n isQualitative: boolean;\n /** Ausente nos biomarcadores sem LOINC publicado, como composição corporal. */\n loincCode?: string;\n /** Lido do `referenceRange.type`, quando o Bundle o traz. */\n referenceKind?: 'decision-threshold' | 'reference-interval';\n referenceMax?: number;\n referenceMin?: number;\n unit: string;\n value: number | string;\n}\n\nexport interface SkippedEntry {\n index: number;\n loincCode?: string;\n reason: string;\n resourceType?: string;\n}\n\nexport interface ImportError {\n details: string;\n field: string;\n}\n\nexport interface FHIRImportResult {\n errors: ImportError[];\n imported: ImportedObservation[];\n skipped: SkippedEntry[];\n totalProcessed: number;\n}\n\n/**\n * Limites de importação.\n *\n * Uma Observation exportada ocupa cerca de 1,25KB em JSON compacto e 2,75KB\n * quando o arquivo vem indentado, medido sobre um histórico real de 998\n * Observations em 61 laudos. Nesse tamanho, 5000 Observations dão 6,0MB\n * compactos ou 13,1MB indentados, e por isso o teto de arquivo é 15MB: cobre\n * as duas formas com folga.\n *\n * Na densidade desse mesmo histórico (16 Observations por laudo), 5000\n * equivalem a cerca de 300 laudos.\n */\nconst MAX_OBSERVATIONS = 5000;\nconst MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB\n\n/**\n * Resolve o código interno do biomarcador a partir do `code.coding`.\n *\n * LOINC primeiro, que é o vocabulário que arquivos de terceiros usam. Quando\n * não resolve, cai para o coding de códigos internos, presente nos arquivos\n * exportados pela própria plataforma.\n *\n * O fallback cobre dois casos: biomarcadores sem LOINC publicado (composição\n * corporal, densidade óssea, escore de cálcio) e arquivos antigos, exportados\n * quando esses biomarcadores saíam com o placeholder `99999-9`, que não\n * resolve para nada.\n */\nfunction resolveBiomarkerCode(observation: FHIRObservation): {\n internalCode?: string;\n loincCode?: string;\n reason: string;\n} {\n const coding = observation.code?.coding ?? [];\n const loincCode = coding.find((c) => c.system === LOINC_SYSTEM)?.code;\n const declaredCode = coding.find((c) => c.system === BIOMARKER_CODE_SYSTEM)?.code;\n\n const seenCodes = [\n ...(loincCode ? [`LOINC ${loincCode}`] : []),\n ...(declaredCode ? [`biomarker code ${declaredCode}`] : []),\n ];\n\n // Três motivos distintos de descarte, que antes se confundiam num só. Sem\n // essa separação, um arquivo em SNOMED relatava \"nenhum código encontrado\",\n // sugerindo `coding` vazio quando na verdade o código existia e estava num\n // system que não tratamos. Para importação de terceiros, é a diferença entre\n // um diagnóstico acionável e um enigma.\n let reason: string;\n if (seenCodes.length > 0) {\n reason = `Unknown code: ${seenCodes.join(', ')}`;\n } else if (coding.length > 0) {\n const systems = [...new Set(coding.map((c) => c.system ?? '(sem system)'))];\n reason = `No code in a supported system (found: ${systems.join(', ')})`;\n } else {\n reason = 'No code found in observation coding';\n }\n\n const fromLoinc = loincCode ? loincToCode(loincCode) : undefined;\n if (fromLoinc) return { internalCode: fromLoinc, loincCode, reason };\n\n if (declaredCode && isValidCode(declaredCode)) {\n // `isValidCode` aceita alias, mas alias não serve como código armazenado:\n // 49 definições têm um, e tanto `codeToLoinc` quanto as faixas de\n // referência são indexadas só pelo canônico. Sem normalizar, `VLDL_Cholesterol`\n // entraria no lugar de `VLDL` e perderia o LOINC 13458-5 que ele tem.\n // Importar um Bundle é fronteira de dados, que é onde `normalizeCode` deve\n // ser aplicado.\n const canonical = normalizeCode(declaredCode);\n\n // `codeToLoinc` devolve undefined para quem não tem LOINC, que é o caso\n // esperado aqui. O campo fica de fora em vez de receber um valor inventado.\n return { internalCode: canonical, loincCode: codeToLoinc(canonical), reason };\n }\n\n return { loincCode, reason };\n}\n\n/**\n * Extract interpretation flag from Observation\n */\nfunction extractFlag(observation: FHIRObservation): 'H' | 'L' | '' {\n const code = observation.interpretation?.[0]?.coding?.[0]?.code;\n if (code === 'H' || code === 'HH') return 'H';\n if (code === 'L' || code === 'LL') return 'L';\n return '';\n}\n\n/**\n * Extract Observation resources from a FHIR Bundle\n */\nexport function extractObservationsFromBundle(bundle: FHIRBundle): {\n observations: FHIRObservation[];\n skipped: SkippedEntry[];\n} {\n const observations: FHIRObservation[] = [];\n const skipped: SkippedEntry[] = [];\n\n for (let i = 0; i < bundle.entry.length; i++) {\n const entry = bundle.entry[i]!;\n if (!entry.resource) {\n skipped.push({ index: i, reason: 'Entry has no resource' });\n continue;\n }\n\n if (entry.resource.resourceType !== 'Observation') {\n // Non-observation resources are silently skipped (Patient, DiagnosticReport, etc.)\n continue;\n }\n\n if (observations.length >= MAX_OBSERVATIONS) {\n skipped.push({ index: i, reason: `Maximum of ${MAX_OBSERVATIONS} observations exceeded` });\n continue;\n }\n\n observations.push(entry.resource as FHIRObservation);\n }\n\n return { observations, skipped };\n}\n\n/**\n * Map a FHIR Observation to internal format using LOINC→biomarker code lookup\n */\nexport function mapFHIRObservationToInternal(\n observation: FHIRObservation,\n index: number,\n): { observation: ImportedObservation } | { skipped: SkippedEntry } {\n const { internalCode, loincCode, reason } = resolveBiomarkerCode(observation);\n\n if (!internalCode) {\n return {\n skipped: { index, loincCode, reason, resourceType: 'Observation' },\n };\n }\n\n const definition = getDefinitionByCode(internalCode);\n\n // Extract value\n let value: number | string;\n let unit = '';\n let isQualitative = false;\n\n if (observation.valueQuantity?.value !== undefined) {\n value = observation.valueQuantity.value;\n unit = observation.valueQuantity.unit || observation.valueQuantity.code || '';\n } else if (observation.valueString) {\n value = observation.valueString;\n isQualitative = true;\n } else {\n return {\n skipped: {\n index,\n loincCode,\n reason: 'Observation has no value (valueQuantity or valueString)',\n resourceType: 'Observation',\n },\n };\n }\n\n // Extract collection date (effectiveDateTime or effectivePeriod.start)\n const collectionDate = observation.effectiveDateTime || observation.effectivePeriod?.start || '';\n if (!collectionDate) {\n return {\n skipped: {\n index,\n loincCode,\n reason: 'Observation has no effectiveDateTime or effectivePeriod.start',\n resourceType: 'Observation',\n },\n };\n }\n\n // Extract reference ranges\n let referenceMin: number | undefined;\n let referenceMax: number | undefined;\n let referenceKind: ImportedObservation['referenceKind'];\n if (observation.referenceRange?.[0]) {\n referenceMin = observation.referenceRange[0].low?.value;\n referenceMax = observation.referenceRange[0].high?.value;\n const meaning = observation.referenceRange[0].type?.coding?.find(\n (c) => c.system === 'http://terminology.hl7.org/CodeSystem/referencerange-meaning',\n )?.code;\n if (meaning === 'normal') referenceKind = 'reference-interval';\n else if (meaning === 'recommended') referenceKind = 'decision-threshold';\n }\n\n const imported: ImportedObservation = {\n biomarkerCode: internalCode,\n biomarkerName:\n definition?.names.pt[0] || definition?.names.en[0] || observation.code.text || internalCode,\n collectionDate,\n flag: extractFlag(observation),\n isQualitative,\n loincCode,\n ...(referenceKind && { referenceKind }),\n referenceMax,\n referenceMin,\n unit: unit || definition?.unit || '',\n value,\n };\n\n return { observation: imported };\n}\n\n/**\n * Process a complete FHIR Bundle for import\n */\nexport function processImportBundle(data: unknown): FHIRImportResult {\n // Structural validation\n const validationErrors = validateFHIRImportBundle(data);\n if (validationErrors.length > 0) {\n return {\n errors: validationErrors,\n imported: [],\n skipped: [],\n totalProcessed: 0,\n };\n }\n\n const bundle = data as FHIRBundle;\n\n // Extract observations\n const { observations, skipped } = extractObservationsFromBundle(bundle);\n\n // Map each observation to internal format\n const imported: ImportedObservation[] = [];\n const allSkipped: SkippedEntry[] = [...skipped];\n\n for (let i = 0; i < observations.length; i++) {\n const result = mapFHIRObservationToInternal(observations[i]!, i);\n\n if ('observation' in result) {\n imported.push(result.observation);\n } else {\n allSkipped.push(result.skipped);\n }\n }\n\n return {\n errors: [],\n imported,\n skipped: allSkipped,\n totalProcessed: observations.length,\n };\n}\n\nexport { MAX_FILE_SIZE, MAX_OBSERVATIONS };\n"]}
|
|
@@ -2,6 +2,9 @@ import {
|
|
|
2
2
|
BIOMARKER_CODE_SYSTEM,
|
|
3
3
|
LOINC_SYSTEM
|
|
4
4
|
} from "./chunk-A6HR4XDK.js";
|
|
5
|
+
import {
|
|
6
|
+
referenceRangeMeaning
|
|
7
|
+
} from "./chunk-P4G534AQ.js";
|
|
5
8
|
import {
|
|
6
9
|
getDefaultUnit,
|
|
7
10
|
resolveUcum
|
|
@@ -59,7 +62,10 @@ var buildReferenceRanges = (observation, quantity) => {
|
|
|
59
62
|
if (observation.referenceRanges && observation.referenceRanges.length > 0) {
|
|
60
63
|
return observation.referenceRanges.flatMap((r) => toRanges(r.low, r.high, r.appliesTo));
|
|
61
64
|
}
|
|
62
|
-
|
|
65
|
+
const meaning = observation.referenceKind && referenceRangeMeaning(observation.referenceKind);
|
|
66
|
+
return toRanges(observation.referenceMin, observation.referenceMax).map(
|
|
67
|
+
(range) => meaning ? { ...range, type: { coding: [meaning] } } : range
|
|
68
|
+
);
|
|
63
69
|
};
|
|
64
70
|
function labObservationToFHIR(observation, patientId, laboratoryName) {
|
|
65
71
|
const loincCode = codeToLoinc(observation.biomarkerCode);
|
|
@@ -265,4 +271,4 @@ export {
|
|
|
265
271
|
userProfileToFHIR,
|
|
266
272
|
labResultToFHIRBundle
|
|
267
273
|
};
|
|
268
|
-
//# sourceMappingURL=chunk-
|
|
274
|
+
//# sourceMappingURL=chunk-K3VZ3F5Z.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bundle-urls.ts","../src/converter.ts"],"sourcesContent":["/**\n * Endereço das entradas de um Bundle.\n *\n * O `fullUrl` identifica a entrada, e é contra ele que o validador resolve as\n * referências entre os recursos. Um Bundle com `subject.reference` valendo\n * `Patient/abc` só resolve se alguma entrada tiver `fullUrl` terminando em\n * `/Patient/abc`: a referência relativa é lida contra a base do `fullUrl` da\n * entrada, que é como os exemplos da própria HL7 montam Bundle de coleção.\n *\n * Antes o `fullUrl` era `urn:uuid:observation-<laudo>-<código>`, que erra duas\n * vezes. `urn:uuid:` exige a sintaxe de UUID e aquilo não era um UUID, e num\n * Bundle de entradas `urn:uuid:` a referência precisa repetir a URN inteira,\n * então nenhuma das relativas resolvia. Um laudo de 22 marcadores saía com 24\n * erros de URN e 22 referências perdidas.\n */\n/**\n * Recurso que já tem id, e por isso pode ser endereçado numa entrada.\n *\n * No FHIR o `id` é opcional, porque um recurso pode viajar sem identidade\n * própria. Numa entrada de Bundle ele não pode: sem id não há `fullUrl`, e sem\n * `fullUrl` nenhuma referência chega ao recurso. Os conversores daqui sempre\n * atribuem um, e o tipo passa a dizer isso em vez de deixar `undefined` chegar\n * até a montagem da URL.\n */\nexport type Addressable<T> = T & { id: string };\n\n/**\n * Base dos `fullUrl`.\n *\n * Não precisa responder a uma requisição: no FHIR o `fullUrl` é identidade, não\n * endereço de download. Fica sob um domínio nosso para não colidir com a\n * identidade de recurso de outra instituição, que é o risco real de usar\n * `example.org` em dado que sai da máquina.\n */\nexport const BUNDLE_BASE_URL = 'https://precisa-saude.com.br/fhir';\n\n/**\n * Monta o `fullUrl` a partir do próprio recurso.\n *\n * Recebe o recurso em vez do tipo e do id soltos de propósito. O defeito que\n * isto substitui nasceu de montar os dois lados em separado: o `fullUrl` dizia\n * `observation-demo-Hgb` enquanto o recurso tinha id `demo-Hgb`, e ninguém\n * percebeu porque nada obrigava os dois a concordarem.\n *\n * O parâmetro pede o mínimo que a URL consome, e não a união de recursos que\n * este pacote converte. Um Bundle pode carregar qualquer recurso do R4, e quem\n * acrescenta uma entrada de um tipo que não está nessa união (um `Specimen`,\n * por exemplo) precisa do mesmo endereço, senão monta o dele e as duas formas\n * divergem outra vez.\n */\nexport const entryFullUrl = (resource: Addressable<{ resourceType: string }>): string =>\n `${BUNDLE_BASE_URL}/${resource.resourceType}/${resource.id}`;\n","/**\n * FHIR Converter\n *\n * Converts lab results to FHIR R4 DiagnosticReport and Observation resources.\n * See: https://hl7.org/fhir/diagnosticreport.html\n */\n\nimport { codeToLoinc } from './biomarkers';\nimport { type Addressable, entryFullUrl } from './bundle-urls';\nimport { BIOMARKER_CODE_SYSTEM, LOINC_SYSTEM } from './code-systems';\nimport type {\n FHIRBundle,\n FHIRDiagnosticReport,\n FHIRObservation,\n FHIRPatient,\n FHIRQuantity,\n FHIRReferenceRange,\n} from './fhir-types';\nimport { referenceRangeMeaning } from './reference-ranges';\nimport type { Flag, LabObservationData, LabReportData, UserProfileData } from './types';\nimport { getDefaultUnit, resolveUcum } from './units';\n\n// Re-export all types and functions\nexport * from './fhir-types';\n\n/**\n * Convert Flag to FHIR interpretation code\n */\nfunction interpretationCode(flag: Flag): string {\n switch (flag) {\n case 'H':\n return 'H'; // High\n case 'L':\n return 'L'; // Low\n default:\n return 'N'; // Normal\n }\n}\n\n/**\n * Convert Flag to FHIR interpretation display\n */\nfunction interpretationDisplay(flag: Flag): string {\n switch (flag) {\n case 'H':\n return 'High';\n case 'L':\n return 'Low';\n default:\n return 'Normal';\n }\n}\n\n/**\n * O `coding` do sexo, que vai **dentro** do CodeableConcept do `appliesTo`.\n *\n * O nome diz `CODING` e não `APPLIES_TO` de propósito: isto não é o valor do\n * campo, é uma entrada da lista de codificações dele. O embrulho acontece no\n * uso, em `{ coding: [SEX_CODING[sex]] }`.\n *\n * É o `AdministrativeGender`, e não o v3-ObservationInterpretation nem um\n * sistema nosso: um consumidor que já lê `Patient.gender` compara os dois sem\n * tabela de tradução no meio.\n */\nconst SEX_CODING = {\n female: {\n code: 'female',\n display: 'Female',\n system: 'http://hl7.org/fhir/administrative-gender',\n },\n male: { code: 'male', display: 'Male', system: 'http://hl7.org/fhir/administrative-gender' },\n} as const;\n\n/**\n * Monta as faixas de referência do `Observation`.\n *\n * Duas mudanças em relação ao que existia, e as duas são sobre não perder o que\n * o laudo imprimiu.\n *\n * **Um limite só já basta.** Antes a faixa só saía com os dois, e um laudo que\n * publica \"inferior a 190 mg/dL\" ou \"superior a 60 mL/min/1,73m²\" perdia o\n * campo inteiro. O R4 trata `low` e `high` como opcionais independentes e\n * documenta o caso de um lado só, e o importador deste mesmo pacote já lia\n * `low?.value` e `high?.value` com acesso opcional: a assimetria era só do\n * escritor. Ver PRE-430.\n *\n * **Mais de uma faixa, anotada.** Laudo com uma coluna de referência por sexo\n * passa a sair com as duas, cada uma com o seu `appliesTo`, em vez de o\n * pipeline escolher uma sem saber de quem é o exame. Ver PRE-424 e PRE-425.\n */\nconst buildReferenceRanges = (\n observation: LabObservationData,\n quantity: (value: number) => FHIRQuantity,\n): FHIRReferenceRange[] => {\n // Devolve lista, e não uma faixa: o caso sem limite nenhum vira lista vazia\n // em vez de `undefined`, e aí os dois caminhos abaixo se compõem com\n // `flatMap` sem ninguém precisar filtrar nada depois.\n const toRanges = (low?: number, high?: number, sex?: 'female' | 'male'): FHIRReferenceRange[] => {\n if (low === undefined && high === undefined) return [];\n\n return [\n {\n ...(sex === undefined ? {} : { appliesTo: [{ coding: [SEX_CODING[sex]] }] }),\n ...(high === undefined ? {} : { high: quantity(high) }),\n ...(low === undefined ? {} : { low: quantity(low) }),\n },\n ];\n };\n\n // A lista anotada tem precedência: quando ela existe, o par simples é o\n // resumo de uma das colunas e repeti-lo publicaria a mesma faixa duas vezes,\n // uma delas sem dizer a quem se aplica.\n //\n // Lista vazia cai no par simples, igual a ausente, e isso é escolha: as duas\n // dizem \"não tenho faixa anotada\", e tratá-las diferente faria um `[]` vindo\n // de um `.filter()` apagar em silêncio a faixa que o chamador também mandou\n // em `referenceMin` e `referenceMax`.\n if (observation.referenceRanges && observation.referenceRanges.length > 0) {\n return observation.referenceRanges.flatMap((r) => toRanges(r.low, r.high, r.appliesTo));\n }\n\n const meaning = observation.referenceKind && referenceRangeMeaning(observation.referenceKind);\n return toRanges(observation.referenceMin, observation.referenceMax).map((range) =>\n meaning ? { ...range, type: { coding: [meaning] } } : range,\n );\n};\n\n/**\n * Convert generic lab observation to FHIR Observation\n */\nexport function labObservationToFHIR(\n observation: LabObservationData,\n patientId: string,\n laboratoryName?: string,\n): Addressable<FHIRObservation> {\n const loincCode = codeToLoinc(observation.biomarkerCode);\n // Use default unit if source unit is empty\n const sourceUnit =\n observation.unit || getDefaultUnit(observation.biomarkerCode) || observation.unit;\n // `system` + `code` só saem quando a unidade resolve em UCUM. Unidade que o\n // pacote não sabe traduzir fica só em `unit`, como texto: afirmar\n // `http://unitsofmeasure.org` sobre `x10^3/mm3` era publicar um código\n // falso, e quem consome o Bundle confiando no system trataria aquilo como\n // UCUM de verdade.\n const ucumUnit = resolveUcum(sourceUnit, observation.biomarkerCode);\n const quantity = (value: number): FHIRQuantity => ({\n ...(ucumUnit ? { code: ucumUnit, system: 'http://unitsofmeasure.org' } : {}),\n ...(sourceUnit ? { unit: sourceUnit } : {}),\n value,\n });\n const isQualitative = observation.isQualitative || typeof observation.value === 'string';\n\n // Base observation structure\n const fhirObs: Addressable<FHIRObservation> = {\n category: [\n {\n coding: [\n {\n code: 'laboratory',\n display: 'Laboratory',\n system: 'http://terminology.hl7.org/CodeSystem/observation-category',\n },\n ],\n },\n ],\n code: {\n // Sem LOINC, o coding LOINC simplesmente não sai. Antes ia `99999-9`,\n // que não é código LOINC nenhum: publicava sob `http://loinc.org` uma\n // afirmação falsa, e quem consumisse o bundle confiando no system\n // trataria aquilo como código de verdade. Composição corporal, densidade\n // óssea e escore de cálcio não têm LOINC, e o certo é a lacuna explícita.\n coding: [\n ...(loincCode\n ? [\n {\n code: loincCode,\n display: observation.biomarkerName,\n system: LOINC_SYSTEM,\n },\n ]\n : []),\n {\n code: observation.biomarkerCode,\n display: observation.biomarkerName,\n system: BIOMARKER_CODE_SYSTEM,\n },\n ],\n text: observation.biomarkerName,\n },\n effectiveDateTime: observation.collectionDate,\n id: `${observation.reportId}-${observation.biomarkerCode}`,\n interpretation: [\n {\n coding: [\n {\n code: interpretationCode(observation.flag),\n display: interpretationDisplay(observation.flag),\n system: 'http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation',\n },\n ],\n },\n ],\n performer: laboratoryName ? [{ display: laboratoryName }] : undefined,\n resourceType: 'Observation',\n status: 'final',\n subject: {\n reference: `Patient/${patientId}`,\n },\n };\n\n // Add value based on type (qualitative = string, quantitative = number)\n if (isQualitative) {\n fhirObs.valueString = String(observation.value);\n } else {\n fhirObs.valueQuantity = quantity(observation.value as number);\n\n // Reference range only applies to quantitative values\n const referenceRange = buildReferenceRanges(observation, quantity);\n if (referenceRange.length > 0) fhirObs.referenceRange = referenceRange;\n }\n\n return fhirObs;\n}\n\n/**\n * Convert generic lab report to FHIR DiagnosticReport\n */\nexport function labReportToFHIR(\n report: LabReportData,\n patientId: string,\n observationIds: string[],\n): Addressable<FHIRDiagnosticReport> {\n // Map processing status to FHIR status\n let status: FHIRDiagnosticReport['status'];\n switch (report.processingStatus) {\n case 'complete':\n status = 'final';\n break;\n case 'partial':\n status = 'partial';\n break;\n case 'pending_review':\n status = 'preliminary';\n break;\n default:\n status = 'final';\n }\n\n return {\n category: [\n {\n coding: [\n {\n code: 'LAB',\n display: 'Laboratory',\n system: 'http://terminology.hl7.org/CodeSystem/v2-0074',\n },\n ],\n },\n ],\n code: {\n coding: [\n {\n code: '11502-2', // Laboratory report\n display: 'Laboratory report',\n system: 'http://loinc.org',\n },\n ],\n text: 'Laboratory Results',\n },\n conclusion:\n report.overallStatus === 'NORMAL'\n ? 'All results within normal limits'\n : 'One or more abnormal results detected',\n conclusionCode:\n report.overallStatus === 'ANORMAL'\n ? [\n {\n coding: [\n {\n code: 'A',\n display: 'Abnormal',\n system: 'http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation',\n },\n ],\n },\n ]\n : undefined,\n effectiveDateTime: report.collectionDate,\n id: report.reportId,\n issued: report.createdAt,\n performer: report.laboratoryName ? [{ display: report.laboratoryName }] : undefined,\n resourceType: 'DiagnosticReport',\n result: observationIds.map((id) => ({ reference: `Observation/${id}` })),\n status,\n subject: {\n reference: `Patient/${patientId}`,\n },\n };\n}\n\n/**\n * Convert user profile to FHIR Patient\n * NOTE: CPF is intentionally excluded for privacy (LGPD compliance)\n */\nexport function userProfileToFHIR(profile: UserProfileData): Addressable<FHIRPatient> {\n const nameParts = profile.name.split(' ');\n const given = nameParts.slice(0, -1);\n const family = nameParts[nameParts.length - 1] || '';\n\n return {\n address: profile.address\n ? [\n {\n city: profile.address.city,\n country: profile.address.country || 'BR',\n line: [\n profile.address.street && profile.address.number\n ? `${profile.address.street}, ${profile.address.number}`\n : profile.address.street,\n profile.address.complement,\n ].filter(Boolean) as string[],\n postalCode: profile.address.postalCode,\n state: profile.address.state,\n },\n ]\n : undefined,\n birthDate: profile.birthDate,\n gender: profile.gender,\n id: profile.userId,\n name: [\n {\n family,\n given: given.length > 0 ? given : undefined,\n text: profile.name,\n },\n ],\n resourceType: 'Patient',\n telecom:\n [\n ...(profile.email ? [{ system: 'email' as const, value: profile.email }] : []),\n ...(profile.phone ? [{ system: 'phone' as const, value: profile.phone }] : []),\n ].length > 0\n ? [\n ...(profile.email ? [{ system: 'email' as const, value: profile.email }] : []),\n ...(profile.phone ? [{ system: 'phone' as const, value: profile.phone }] : []),\n ]\n : undefined,\n };\n}\n\n/**\n * Convert complete lab result to FHIR Bundle\n * This is the main function for exporting lab results to FHIR R4 format\n */\nexport function labResultToFHIRBundle(\n report: LabReportData,\n observations: LabObservationData[],\n userProfile: UserProfileData,\n): FHIRBundle {\n const patientId = userProfile.userId;\n\n // Convert observations\n const fhirObservations = observations.map((obs) => {\n const resource = labObservationToFHIR(\n { ...obs, collectionDate: report.collectionDate },\n patientId,\n report.laboratoryName,\n );\n\n return { fullUrl: entryFullUrl(resource), resource };\n });\n\n // Os ids vêm dos recursos já montados, e não de uma segunda montagem da mesma\n // regra. O `DiagnosticReport.result` aponta para eles, e era aqui que a\n // referência se separava do recurso.\n const observationIds = fhirObservations.map((entry) => entry.resource.id);\n\n // Convert report\n const diagnosticReport = labReportToFHIR(report, patientId, observationIds);\n\n // Convert patient\n const fhirPatient = userProfileToFHIR(userProfile);\n\n return {\n entry: [\n { fullUrl: entryFullUrl(fhirPatient), resource: fhirPatient },\n { fullUrl: entryFullUrl(diagnosticReport), resource: diagnosticReport },\n ...fhirObservations,\n ],\n resourceType: 'Bundle',\n type: 'collection',\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkCO,IAAM,kBAAkB;AAgBxB,IAAM,eAAe,CAAC,aAC3B,GAAG,eAAe,IAAI,SAAS,YAAY,IAAI,SAAS,EAAE;;;ACvB5D,SAAS,mBAAmB,MAAoB;AAC9C,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO;AAAA;AAAA,IACT,KAAK;AACH,aAAO;AAAA;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAKA,SAAS,sBAAsB,MAAoB;AACjD,UAAQ,MAAM;AAAA,IACZ,KAAK;AACH,aAAO;AAAA,IACT,KAAK;AACH,aAAO;AAAA,IACT;AACE,aAAO;AAAA,EACX;AACF;AAaA,IAAM,aAAa;AAAA,EACjB,QAAQ;AAAA,IACN,MAAM;AAAA,IACN,SAAS;AAAA,IACT,QAAQ;AAAA,EACV;AAAA,EACA,MAAM,EAAE,MAAM,QAAQ,SAAS,QAAQ,QAAQ,4CAA4C;AAC7F;AAmBA,IAAM,uBAAuB,CAC3B,aACA,aACyB;AAIzB,QAAM,WAAW,CAAC,KAAc,MAAe,QAAkD;AAC/F,QAAI,QAAQ,UAAa,SAAS,OAAW,QAAO,CAAC;AAErD,WAAO;A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CAAC,UAAU,MAAM,SAAS,EAAE;AAGxE,QAAM,mBAAmB,gBAAgB,QAAQ,WAAW,cAAc;AAG1E,QAAM,cAAc,kBAAkB,WAAW;AAEjD,SAAO;AAAA,IACL,OAAO;AAAA,MACL,EAAE,SAAS,aAAa,WAAW,GAAG,UAAU,YAAY;AAAA,MAC5D,EAAE,SAAS,aAAa,gBAAgB,GAAG,UAAU,iBAAiB;AAAA,MACtE,GAAG;AAAA,IACL;AAAA,IACA,cAAc;AAAA,IACd,MAAM;AAAA,EACR;AACF;","names":[]}
|
|
@@ -107,9 +107,15 @@ function mapFHIRObservationToInternal(observation, index) {
|
|
|
107
107
|
}
|
|
108
108
|
let referenceMin;
|
|
109
109
|
let referenceMax;
|
|
110
|
+
let referenceKind;
|
|
110
111
|
if (observation.referenceRange?.[0]) {
|
|
111
112
|
referenceMin = observation.referenceRange[0].low?.value;
|
|
112
113
|
referenceMax = observation.referenceRange[0].high?.value;
|
|
114
|
+
const meaning = observation.referenceRange[0].type?.coding?.find(
|
|
115
|
+
(c) => c.system === "http://terminology.hl7.org/CodeSystem/referencerange-meaning"
|
|
116
|
+
)?.code;
|
|
117
|
+
if (meaning === "normal") referenceKind = "reference-interval";
|
|
118
|
+
else if (meaning === "recommended") referenceKind = "decision-threshold";
|
|
113
119
|
}
|
|
114
120
|
const imported = {
|
|
115
121
|
biomarkerCode: internalCode,
|
|
@@ -118,6 +124,7 @@ function mapFHIRObservationToInternal(observation, index) {
|
|
|
118
124
|
flag: extractFlag(observation),
|
|
119
125
|
isQualitative,
|
|
120
126
|
loincCode,
|
|
127
|
+
...referenceKind && { referenceKind },
|
|
121
128
|
referenceMax,
|
|
122
129
|
referenceMin,
|
|
123
130
|
unit: unit || definition?.unit || "",
|
|
@@ -162,4 +169,4 @@ export {
|
|
|
162
169
|
mapFHIRObservationToInternal,
|
|
163
170
|
processImportBundle
|
|
164
171
|
};
|
|
165
|
-
//# sourceMappingURL=chunk-
|
|
172
|
+
//# sourceMappingURL=chunk-NJM45WAH.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/importer.ts"],"sourcesContent":["/**\n * FHIR Importer\n *\n * Parses FHIR R4 Bundles and extracts Observation resources with known LOINC codes,\n * mapping them to internal biomarker codes for storage as lab results.\n */\n\nimport {\n codeToLoinc,\n getDefinitionByCode,\n isValidCode,\n loincToCode,\n normalizeCode,\n} from './biomarkers';\nimport { BIOMARKER_CODE_SYSTEM, LOINC_SYSTEM } from './code-systems';\nimport type { FHIRBundle, FHIRObservation } from './fhir-types';\nimport { validateFHIRImportBundle } from './validators';\n\nexport interface ImportedObservation {\n biomarkerCode: string;\n biomarkerName: string;\n collectionDate: string;\n flag: 'H' | 'L' | '';\n isQualitative: boolean;\n /** Ausente nos biomarcadores sem LOINC publicado, como composição corporal. */\n loincCode?: string;\n /** Lido do `referenceRange.type`, quando o Bundle o traz. */\n referenceKind?: 'decision-threshold' | 'reference-interval';\n referenceMax?: number;\n referenceMin?: number;\n unit: string;\n value: number | string;\n}\n\nexport interface SkippedEntry {\n index: number;\n loincCode?: string;\n reason: string;\n resourceType?: string;\n}\n\nexport interface ImportError {\n details: string;\n field: string;\n}\n\nexport interface FHIRImportResult {\n errors: ImportError[];\n imported: ImportedObservation[];\n skipped: SkippedEntry[];\n totalProcessed: number;\n}\n\n/**\n * Limites de importação.\n *\n * Uma Observation exportada ocupa cerca de 1,25KB em JSON compacto e 2,75KB\n * quando o arquivo vem indentado, medido sobre um histórico real de 998\n * Observations em 61 laudos. Nesse tamanho, 5000 Observations dão 6,0MB\n * compactos ou 13,1MB indentados, e por isso o teto de arquivo é 15MB: cobre\n * as duas formas com folga.\n *\n * Na densidade desse mesmo histórico (16 Observations por laudo), 5000\n * equivalem a cerca de 300 laudos.\n */\nconst MAX_OBSERVATIONS = 5000;\nconst MAX_FILE_SIZE = 15 * 1024 * 1024; // 15MB\n\n/**\n * Resolve o código interno do biomarcador a partir do `code.coding`.\n *\n * LOINC primeiro, que é o vocabulário que arquivos de terceiros usam. Quando\n * não resolve, cai para o coding de códigos internos, presente nos arquivos\n * exportados pela própria plataforma.\n *\n * O fallback cobre dois casos: biomarcadores sem LOINC publicado (composição\n * corporal, densidade óssea, escore de cálcio) e arquivos antigos, exportados\n * quando esses biomarcadores saíam com o placeholder `99999-9`, que não\n * resolve para nada.\n */\nfunction resolveBiomarkerCode(observation: FHIRObservation): {\n internalCode?: string;\n loincCode?: string;\n reason: string;\n} {\n const coding = observation.code?.coding ?? [];\n const loincCode = coding.find((c) => c.system === LOINC_SYSTEM)?.code;\n const declaredCode = coding.find((c) => c.system === BIOMARKER_CODE_SYSTEM)?.code;\n\n const seenCodes = [\n ...(loincCode ? [`LOINC ${loincCode}`] : []),\n ...(declaredCode ? [`biomarker code ${declaredCode}`] : []),\n ];\n\n // Três motivos distintos de descarte, que antes se confundiam num só. Sem\n // essa separação, um arquivo em SNOMED relatava \"nenhum código encontrado\",\n // sugerindo `coding` vazio quando na verdade o código existia e estava num\n // system que não tratamos. Para importação de terceiros, é a diferença entre\n // um diagnóstico acionável e um enigma.\n let reason: string;\n if (seenCodes.length > 0) {\n reason = `Unknown code: ${seenCodes.join(', ')}`;\n } else if (coding.length > 0) {\n const systems = [...new Set(coding.map((c) => c.system ?? '(sem system)'))];\n reason = `No code in a supported system (found: ${systems.join(', ')})`;\n } else {\n reason = 'No code found in observation coding';\n }\n\n const fromLoinc = loincCode ? loincToCode(loincCode) : undefined;\n if (fromLoinc) return { internalCode: fromLoinc, loincCode, reason };\n\n if (declaredCode && isValidCode(declaredCode)) {\n // `isValidCode` aceita alias, mas alias não serve como código armazenado:\n // 49 definições têm um, e tanto `codeToLoinc` quanto as faixas de\n // referência são indexadas só pelo canônico. Sem normalizar, `VLDL_Cholesterol`\n // entraria no lugar de `VLDL` e perderia o LOINC 13458-5 que ele tem.\n // Importar um Bundle é fronteira de dados, que é onde `normalizeCode` deve\n // ser aplicado.\n const canonical = normalizeCode(declaredCode);\n\n // `codeToLoinc` devolve undefined para quem não tem LOINC, que é o caso\n // esperado aqui. O campo fica de fora em vez de receber um valor inventado.\n return { internalCode: canonical, loincCode: codeToLoinc(canonical), reason };\n }\n\n return { loincCode, reason };\n}\n\n/**\n * Extract interpretation flag from Observation\n */\nfunction extractFlag(observation: FHIRObservation): 'H' | 'L' | '' {\n const code = observation.interpretation?.[0]?.coding?.[0]?.code;\n if (code === 'H' || code === 'HH') return 'H';\n if (code === 'L' || code === 'LL') return 'L';\n return '';\n}\n\n/**\n * Extract Observation resources from a FHIR Bundle\n */\nexport function extractObservationsFromBundle(bundle: FHIRBundle): {\n observations: FHIRObservation[];\n skipped: SkippedEntry[];\n} {\n const observations: FHIRObservation[] = [];\n const skipped: SkippedEntry[] = [];\n\n for (let i = 0; i < bundle.entry.length; i++) {\n const entry = bundle.entry[i]!;\n if (!entry.resource) {\n skipped.push({ index: i, reason: 'Entry has no resource' });\n continue;\n }\n\n if (entry.resource.resourceType !== 'Observation') {\n // Non-observation resources are silently skipped (Patient, DiagnosticReport, etc.)\n continue;\n }\n\n if (observations.length >= MAX_OBSERVATIONS) {\n skipped.push({ index: i, reason: `Maximum of ${MAX_OBSERVATIONS} observations exceeded` });\n continue;\n }\n\n observations.push(entry.resource as FHIRObservation);\n }\n\n return { observations, skipped };\n}\n\n/**\n * Map a FHIR Observation to internal format using LOINC→biomarker code lookup\n */\nexport function mapFHIRObservationToInternal(\n observation: FHIRObservation,\n index: number,\n): { observation: ImportedObservation } | { skipped: SkippedEntry } {\n const { internalCode, loincCode, reason } = resolveBiomarkerCode(observation);\n\n if (!internalCode) {\n return {\n skipped: { index, loincCode, reason, resourceType: 'Observation' },\n };\n }\n\n const definition = getDefinitionByCode(internalCode);\n\n // Extract value\n let value: number | string;\n let unit = '';\n let isQualitative = false;\n\n if (observation.valueQuantity?.value !== undefined) {\n value = observation.valueQuantity.value;\n unit = observation.valueQuantity.unit || observation.valueQuantity.code || '';\n } else if (observation.valueString) {\n value = observation.valueString;\n isQualitative = true;\n } else {\n return {\n skipped: {\n index,\n loincCode,\n reason: 'Observation has no value (valueQuantity or valueString)',\n resourceType: 'Observation',\n },\n };\n }\n\n // Extract collection date (effectiveDateTime or effectivePeriod.start)\n const collectionDate = observation.effectiveDateTime || observation.effectivePeriod?.start || '';\n if (!collectionDate) {\n return {\n skipped: {\n index,\n loincCode,\n reason: 'Observation has no effectiveDateTime or effectivePeriod.start',\n resourceType: 'Observation',\n },\n };\n }\n\n // Extract reference ranges\n let referenceMin: number | undefined;\n let referenceMax: number | undefined;\n let referenceKind: ImportedObservation['referenceKind'];\n if (observation.referenceRange?.[0]) {\n referenceMin = observation.referenceRange[0].low?.value;\n referenceMax = observation.referenceRange[0].high?.value;\n const meaning = observation.referenceRange[0].type?.coding?.find(\n (c) => c.system === 'http://terminology.hl7.org/CodeSystem/referencerange-meaning',\n )?.code;\n if (meaning === 'normal') referenceKind = 'reference-interval';\n else if (meaning === 'recommended') referenceKind = 'decision-threshold';\n }\n\n const imported: ImportedObservation = {\n biomarkerCode: internalCode,\n biomarkerName:\n definition?.names.pt[0] || definition?.names.en[0] || observation.code.text || internalCode,\n collectionDate,\n flag: extractFlag(observation),\n isQualitative,\n loincCode,\n ...(referenceKind && { referenceKind }),\n referenceMax,\n referenceMin,\n unit: unit || definition?.unit || '',\n value,\n };\n\n return { observation: imported };\n}\n\n/**\n * Process a complete FHIR Bundle for import\n */\nexport function processImportBundle(data: unknown): FHIRImportResult {\n // Structural validation\n const validationErrors = validateFHIRImportBundle(data);\n if (validationErrors.length > 0) {\n return {\n errors: validationErrors,\n imported: [],\n skipped: [],\n totalProcessed: 0,\n };\n }\n\n const bundle = data as FHIRBundle;\n\n // Extract observations\n const { observations, skipped } = extractObservationsFromBundle(bundle);\n\n // Map each observation to internal format\n const imported: ImportedObservation[] = [];\n const allSkipped: SkippedEntry[] = [...skipped];\n\n for (let i = 0; i < observations.length; i++) {\n const result = mapFHIRObservationToInternal(observations[i]!, i);\n\n if ('observation' in result) {\n imported.push(result.observation);\n } else {\n allSkipped.push(result.skipped);\n }\n }\n\n return {\n errors: [],\n imported,\n skipped: allSkipped,\n totalProcessed: observations.length,\n };\n}\n\nexport { MAX_FILE_SIZE, MAX_OBSERVATIONS };\n"],"mappings":";;;;;;;;;;;;;;;;AAiEA,IAAM,mBAAmB;AACzB,IAAM,gBAAgB,KAAK,OAAO;AAclC,SAAS,qBAAqB,aAI5B;AACA,QAAM,SAAS,YAAY,MAAM,UAAU,CAAC;AAC5C,QAAM,YAAY,OAAO,KAAK,CAAC,MAAM,EAAE,WAAW,YAAY,GAAG;AACjE,QAAM,eAAe,OAAO,KAAK,CAAC,MAAM,EAAE,WAAW,qBAAqB,GAAG;AAE7E,QAAM,YAAY;AAAA,IAChB,GAAI,YAAY,CAAC,SAAS,SAAS,EAAE,IAAI,CAAC;AAAA,IAC1C,GAAI,eAAe,CAAC,kBAAkB,YAAY,EAAE,IAAI,CAAC;AAAA,EAC3D;AAOA,MAAI;AACJ,MAAI,UAAU,SAAS,GAAG;AACxB,aAAS,iBAAiB,UAAU,KAAK,IAAI,CAAC;AAAA,EAChD,WAAW,OAAO,SAAS,GAAG;AAC5B,UAAM,UAAU,CAAC,GAAG,IAAI,IAAI,OAAO,IAAI,CAAC,MAAM,EAAE,UAAU,cAAc,CAAC,CAAC;AAC1E,aAAS,yCAAyC,QAAQ,KAAK,IAAI,CAAC;AAAA,EACtE,OAAO;AACL,aAAS;AAAA,EACX;AAEA,QAAM,YAAY,YAAY,YAAY,SAAS,IAAI;AACvD,MAAI,UAAW,QAAO,EAAE,cAAc,WAAW,WAAW,OAAO;AAEnE,MAAI,gBAAgB,YAAY,YAAY,GAAG;AAO7C,UAAM,YAAY,cAAc,YAAY;AAI5C,WAAO,EAAE,cAAc,WAAW,WAAW,YAAY,SAAS,GAAG,OAAO;AAAA,EAC9E;AAEA,SAAO,EAAE,WAAW,OAAO;AAC7B;AAKA,SAAS,YAAY,aAA8C;AACjE,QAAM,OAAO,YAAY,iBAAiB,CAAC,GA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AM,WAAkC,CAAC;AACzC,QAAM,aAA6B,CAAC,GAAG,OAAO;AAE9C,WAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,UAAM,SAAS,6BAA6B,aAAa,CAAC,GAAI,CAAC;AAE/D,QAAI,iBAAiB,QAAQ;AAC3B,eAAS,KAAK,OAAO,WAAW;AAAA,IAClC,OAAO;AACL,iBAAW,KAAK,OAAO,OAAO;AAAA,IAChC;AAAA,EACF;AAEA,SAAO;AAAA,IACL,QAAQ,CAAC;AAAA,IACT;AAAA,IACA,SAAS;AAAA,IACT,gBAAgB,aAAa;AAAA,EAC/B;AACF;","names":[]}
|
|
@@ -4,6 +4,9 @@
|
|
|
4
4
|
var _chunkOR67NJDZcjs = require('./chunk-OR67NJDZ.cjs');
|
|
5
5
|
|
|
6
6
|
|
|
7
|
+
var _chunkVKLWTTUOcjs = require('./chunk-VKLWTTUO.cjs');
|
|
8
|
+
|
|
9
|
+
|
|
7
10
|
|
|
8
11
|
var _chunk5RC7C7HJcjs = require('./chunk-5RC7C7HJ.cjs');
|
|
9
12
|
|
|
@@ -59,7 +62,10 @@ var buildReferenceRanges = (observation, quantity) => {
|
|
|
59
62
|
if (observation.referenceRanges && observation.referenceRanges.length > 0) {
|
|
60
63
|
return observation.referenceRanges.flatMap((r) => toRanges(r.low, r.high, r.appliesTo));
|
|
61
64
|
}
|
|
62
|
-
|
|
65
|
+
const meaning = observation.referenceKind && _chunkVKLWTTUOcjs.referenceRangeMeaning.call(void 0, observation.referenceKind);
|
|
66
|
+
return toRanges(observation.referenceMin, observation.referenceMax).map(
|
|
67
|
+
(range) => meaning ? { ...range, type: { coding: [meaning] } } : range
|
|
68
|
+
);
|
|
63
69
|
};
|
|
64
70
|
function labObservationToFHIR(observation, patientId, laboratoryName) {
|
|
65
71
|
const loincCode = _chunkT75NZM56cjs.codeToLoinc.call(void 0, observation.biomarkerCode);
|
|
@@ -265,4 +271,4 @@ function labResultToFHIRBundle(report, observations, userProfile) {
|
|
|
265
271
|
|
|
266
272
|
|
|
267
273
|
exports.BUNDLE_BASE_URL = BUNDLE_BASE_URL; exports.entryFullUrl = entryFullUrl; exports.labObservationToFHIR = labObservationToFHIR; exports.labReportToFHIR = labReportToFHIR; exports.userProfileToFHIR = userProfileToFHIR; exports.labResultToFHIRBundle = labResultToFHIRBundle;
|
|
268
|
-
//# sourceMappingURL=chunk-
|
|
274
|
+
//# sourceMappingURL=chunk-NKDUVSDK.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-NKDUVSDK.cjs","../src/bundle-urls.ts","../src/converter.ts"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACF,wDAA6B;AAC7B;AACA;ACmBO,IAAM,gBAAA,EAAkB,mCAAA;AAgBxB,IAAM,aAAA,EAAe,CAAC,QAAA,EAAA,GAC3B,CAAA,EAAA;ADjCgC;AACA;AESc;AAChC,EAAA;AACP,IAAA;AACI,MAAA;AAAA;AACJ,IAAA;AACI,MAAA;AAAA;AACT,IAAA;AACS,MAAA;AACX,EAAA;AACF;AAK+B;AACf,EAAA;AACP,IAAA;AACI,MAAA;AACJ,IAAA;AACI,MAAA;AACT,IAAA;AACS,MAAA;AACX,EAAA;AACF;AAamB;AACT,EAAA;AACA,IAAA;AACG,IAAA;AACD,IAAA;AACV,EAAA;AAC+B,EAAA;AACjC;AAoBE;AAM+C,EAAA;AACpB,IAAA;AAElB,IAAA;AACL,MAAA;AAC+B,QAAA;AACC,QAAA;AACD,QAAA;AAC/B,MAAA;AACF,IAAA;AACF,EAAA;AAUgB,EAAA;AACK,IAAA;AACrB,EAAA;AAE4B,EAAA;AACA,EAAA;AACX,IAAA;AACjB,EAAA;AACF;AAME;AAI8B,EAAA;AAGhB,EAAA;AAMe,EAAA;AACsB,EAAA;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A;AACV,UAAA;AACF,QAAA;AACF,MAAA;AAEF,IAAA;AACoB,IAAA;AACf,IAAA;AACI,IAAA;AACG,IAAA;AACJ,IAAA;AACc,IAAA;AAC5B,IAAA;AACS,IAAA;AACe,MAAA;AACxB,IAAA;AACF,EAAA;AACF;AAMkC;AACD,EAAA;AACD,EAAA;AACL,EAAA;AAElB,EAAA;AAED,IAAA;AACE,MAAA;AACwB,QAAA;AACG,QAAA;AACnB,QAAA;AACY,UAAA;AAGA,UAAA;AACF,QAAA;AACI,QAAA;AACG,QAAA;AACzB,MAAA;AAEF,IAAA;AACe,IAAA;AACH,IAAA;AACJ,IAAA;AACN,IAAA;AACJ,MAAA;AACE,QAAA;AAC0B,QAAA;AACZ,QAAA;AAChB,MAAA;AACF,IAAA;AACc,IAAA;AAEZ,IAAA;AACyB,MAAA;AACA,MAAA;AAErB,IAAA;AACyB,MAAA;AACA,MAAA;AAEzB,IAAA;AACR,EAAA;AACF;AAOE;AAI8B,EAAA;AAGL,EAAA;AACN,IAAA;AACW,MAAA;AAC1B,MAAA;AACO,MAAA;AACT,IAAA;AAEkB,IAAA;AACnB,EAAA;AAKsB,EAAA;AAGE,EAAA;AAGL,EAAA;AAEb,EAAA;AACE,IAAA;AACmB,MAAA;AACA,MAAA;AACrB,MAAA;AACL,IAAA;AACc,IAAA;AACR,IAAA;AACR,EAAA;AACF;AFjIkC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-NKDUVSDK.cjs","sourcesContent":[null,"/**\n * Endereço das entradas de um Bundle.\n *\n * O `fullUrl` identifica a entrada, e é contra ele que o validador resolve as\n * referências entre os recursos. Um Bundle com `subject.reference` valendo\n * `Patient/abc` só resolve se alguma entrada tiver `fullUrl` terminando em\n * `/Patient/abc`: a referência relativa é lida contra a base do `fullUrl` da\n * entrada, que é como os exemplos da própria HL7 montam Bundle de coleção.\n *\n * Antes o `fullUrl` era `urn:uuid:observation-<laudo>-<código>`, que erra duas\n * vezes. `urn:uuid:` exige a sintaxe de UUID e aquilo não era um UUID, e num\n * Bundle de entradas `urn:uuid:` a referência precisa repetir a URN inteira,\n * então nenhuma das relativas resolvia. Um laudo de 22 marcadores saía com 24\n * erros de URN e 22 referências perdidas.\n */\n/**\n * Recurso que já tem id, e por isso pode ser endereçado numa entrada.\n *\n * No FHIR o `id` é opcional, porque um recurso pode viajar sem identidade\n * própria. Numa entrada de Bundle ele não pode: sem id não há `fullUrl`, e sem\n * `fullUrl` nenhuma referência chega ao recurso. Os conversores daqui sempre\n * atribuem um, e o tipo passa a dizer isso em vez de deixar `undefined` chegar\n * até a montagem da URL.\n */\nexport type Addressable<T> = T & { id: string };\n\n/**\n * Base dos `fullUrl`.\n *\n * Não precisa responder a uma requisição: no FHIR o `fullUrl` é identidade, não\n * endereço de download. Fica sob um domínio nosso para não colidir com a\n * identidade de recurso de outra instituição, que é o risco real de usar\n * `example.org` em dado que sai da máquina.\n */\nexport const BUNDLE_BASE_URL = 'https://precisa-saude.com.br/fhir';\n\n/**\n * Monta o `fullUrl` a partir do próprio recurso.\n *\n * Recebe o recurso em vez do tipo e do id soltos de propósito. O defeito que\n * isto substitui nasceu de montar os dois lados em separado: o `fullUrl` dizia\n * `observation-demo-Hgb` enquanto o recurso tinha id `demo-Hgb`, e ninguém\n * percebeu porque nada obrigava os dois a concordarem.\n *\n * O parâmetro pede o mínimo que a URL consome, e não a união de recursos que\n * este pacote converte. Um Bundle pode carregar qualquer recurso do R4, e quem\n * acrescenta uma entrada de um tipo que não está nessa união (um `Specimen`,\n * por exemplo) precisa do mesmo endereço, senão monta o dele e as duas formas\n * divergem outra vez.\n */\nexport const entryFullUrl = (resource: Addressable<{ resourceType: string }>): string =>\n `${BUNDLE_BASE_URL}/${resource.resourceType}/${resource.id}`;\n","/**\n * FHIR Converter\n *\n * Converts lab results to FHIR R4 DiagnosticReport and Observation resources.\n * See: https://hl7.org/fhir/diagnosticreport.html\n */\n\nimport { codeToLoinc } from './biomarkers';\nimport { type Addressable, entryFullUrl } from './bundle-urls';\nimport { BIOMARKER_CODE_SYSTEM, LOINC_SYSTEM } from './code-systems';\nimport type {\n FHIRBundle,\n FHIRDiagnosticReport,\n FHIRObservation,\n FHIRPatient,\n FHIRQuantity,\n FHIRReferenceRange,\n} from './fhir-types';\nimport { referenceRangeMeaning } from './reference-ranges';\nimport type { Flag, LabObservationData, LabReportData, UserProfileData } from './types';\nimport { getDefaultUnit, resolveUcum } from './units';\n\n// Re-export all types and functions\nexport * from './fhir-types';\n\n/**\n * Convert Flag to FHIR interpretation code\n */\nfunction interpretationCode(flag: Flag): string {\n switch (flag) {\n case 'H':\n return 'H'; // High\n case 'L':\n return 'L'; // Low\n default:\n return 'N'; // Normal\n }\n}\n\n/**\n * Convert Flag to FHIR interpretation display\n */\nfunction interpretationDisplay(flag: Flag): string {\n switch (flag) {\n case 'H':\n return 'High';\n case 'L':\n return 'Low';\n default:\n return 'Normal';\n }\n}\n\n/**\n * O `coding` do sexo, que vai **dentro** do CodeableConcept do `appliesTo`.\n *\n * O nome diz `CODING` e não `APPLIES_TO` de propósito: isto não é o valor do\n * campo, é uma entrada da lista de codificações dele. O embrulho acontece no\n * uso, em `{ coding: [SEX_CODING[sex]] }`.\n *\n * É o `AdministrativeGender`, e não o v3-ObservationInterpretation nem um\n * sistema nosso: um consumidor que já lê `Patient.gender` compara os dois sem\n * tabela de tradução no meio.\n */\nconst SEX_CODING = {\n female: {\n code: 'female',\n display: 'Female',\n system: 'http://hl7.org/fhir/administrative-gender',\n },\n male: { code: 'male', display: 'Male', system: 'http://hl7.org/fhir/administrative-gender' },\n} as const;\n\n/**\n * Monta as faixas de referência do `Observation`.\n *\n * Duas mudanças em relação ao que existia, e as duas são sobre não perder o que\n * o laudo imprimiu.\n *\n * **Um limite só já basta.** Antes a faixa só saía com os dois, e um laudo que\n * publica \"inferior a 190 mg/dL\" ou \"superior a 60 mL/min/1,73m²\" perdia o\n * campo inteiro. O R4 trata `low` e `high` como opcionais independentes e\n * documenta o caso de um lado só, e o importador deste mesmo pacote já lia\n * `low?.value` e `high?.value` com acesso opcional: a assimetria era só do\n * escritor. Ver PRE-430.\n *\n * **Mais de uma faixa, anotada.** Laudo com uma coluna de referência por sexo\n * passa a sair com as duas, cada uma com o seu `appliesTo`, em vez de o\n * pipeline escolher uma sem saber de quem é o exame. Ver PRE-424 e PRE-425.\n */\nconst buildReferenceRanges = (\n observation: LabObservationData,\n quantity: (value: number) => FHIRQuantity,\n): FHIRReferenceRange[] => {\n // Devolve lista, e não uma faixa: o caso sem limite nenhum vira lista vazia\n // em vez de `undefined`, e aí os dois caminhos abaixo se compõem com\n // `flatMap` sem ninguém precisar filtrar nada depois.\n const toRanges = (low?: number, high?: number, sex?: 'female' | 'male'): FHIRReferenceRange[] => {\n if (low === undefined && high === undefined) return [];\n\n return [\n {\n ...(sex === undefined ? {} : { appliesTo: [{ coding: [SEX_CODING[sex]] }] }),\n ...(high === undefined ? {} : { high: quantity(high) }),\n ...(low === undefined ? {} : { low: quantity(low) }),\n },\n ];\n };\n\n // A lista anotada tem precedência: quando ela existe, o par simples é o\n // resumo de uma das colunas e repeti-lo publicaria a mesma faixa duas vezes,\n // uma delas sem dizer a quem se aplica.\n //\n // Lista vazia cai no par simples, igual a ausente, e isso é escolha: as duas\n // dizem \"não tenho faixa anotada\", e tratá-las diferente faria um `[]` vindo\n // de um `.filter()` apagar em silêncio a faixa que o chamador também mandou\n // em `referenceMin` e `referenceMax`.\n if (observation.referenceRanges && observation.referenceRanges.length > 0) {\n return observation.referenceRanges.flatMap((r) => toRanges(r.low, r.high, r.appliesTo));\n }\n\n const meaning = observation.referenceKind && referenceRangeMeaning(observation.referenceKind);\n return toRanges(observation.referenceMin, observation.referenceMax).map((range) =>\n meaning ? { ...range, type: { coding: [meaning] } } : range,\n );\n};\n\n/**\n * Convert generic lab observation to FHIR Observation\n */\nexport function labObservationToFHIR(\n observation: LabObservationData,\n patientId: string,\n laboratoryName?: string,\n): Addressable<FHIRObservation> {\n const loincCode = codeToLoinc(observation.biomarkerCode);\n // Use default unit if source unit is empty\n const sourceUnit =\n observation.unit || getDefaultUnit(observation.biomarkerCode) || observation.unit;\n // `system` + `code` só saem quando a unidade resolve em UCUM. Unidade que o\n // pacote não sabe traduzir fica só em `unit`, como texto: afirmar\n // `http://unitsofmeasure.org` sobre `x10^3/mm3` era publicar um código\n // falso, e quem consome o Bundle confiando no system trataria aquilo como\n // UCUM de verdade.\n const ucumUnit = resolveUcum(sourceUnit, observation.biomarkerCode);\n const quantity = (value: number): FHIRQuantity => ({\n ...(ucumUnit ? { code: ucumUnit, system: 'http://unitsofmeasure.org' } : {}),\n ...(sourceUnit ? { unit: sourceUnit } : {}),\n value,\n });\n const isQualitative = observation.isQualitative || typeof observation.value === 'string';\n\n // Base observation structure\n const fhirObs: Addressable<FHIRObservation> = {\n category: [\n {\n coding: [\n {\n code: 'laboratory',\n display: 'Laboratory',\n system: 'http://terminology.hl7.org/CodeSystem/observation-category',\n },\n ],\n },\n ],\n code: {\n // Sem LOINC, o coding LOINC simplesmente não sai. Antes ia `99999-9`,\n // que não é código LOINC nenhum: publicava sob `http://loinc.org` uma\n // afirmação falsa, e quem consumisse o bundle confiando no system\n // trataria aquilo como código de verdade. Composição corporal, densidade\n // óssea e escore de cálcio não têm LOINC, e o certo é a lacuna explícita.\n coding: [\n ...(loincCode\n ? [\n {\n code: loincCode,\n display: observation.biomarkerName,\n system: LOINC_SYSTEM,\n },\n ]\n : []),\n {\n code: observation.biomarkerCode,\n display: observation.biomarkerName,\n system: BIOMARKER_CODE_SYSTEM,\n },\n ],\n text: observation.biomarkerName,\n },\n effectiveDateTime: observation.collectionDate,\n id: `${observation.reportId}-${observation.biomarkerCode}`,\n interpretation: [\n {\n coding: [\n {\n code: interpretationCode(observation.flag),\n display: interpretationDisplay(observation.flag),\n system: 'http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation',\n },\n ],\n },\n ],\n performer: laboratoryName ? [{ display: laboratoryName }] : undefined,\n resourceType: 'Observation',\n status: 'final',\n subject: {\n reference: `Patient/${patientId}`,\n },\n };\n\n // Add value based on type (qualitative = string, quantitative = number)\n if (isQualitative) {\n fhirObs.valueString = String(observation.value);\n } else {\n fhirObs.valueQuantity = quantity(observation.value as number);\n\n // Reference range only applies to quantitative values\n const referenceRange = buildReferenceRanges(observation, quantity);\n if (referenceRange.length > 0) fhirObs.referenceRange = referenceRange;\n }\n\n return fhirObs;\n}\n\n/**\n * Convert generic lab report to FHIR DiagnosticReport\n */\nexport function labReportToFHIR(\n report: LabReportData,\n patientId: string,\n observationIds: string[],\n): Addressable<FHIRDiagnosticReport> {\n // Map processing status to FHIR status\n let status: FHIRDiagnosticReport['status'];\n switch (report.processingStatus) {\n case 'complete':\n status = 'final';\n break;\n case 'partial':\n status = 'partial';\n break;\n case 'pending_review':\n status = 'preliminary';\n break;\n default:\n status = 'final';\n }\n\n return {\n category: [\n {\n coding: [\n {\n code: 'LAB',\n display: 'Laboratory',\n system: 'http://terminology.hl7.org/CodeSystem/v2-0074',\n },\n ],\n },\n ],\n code: {\n coding: [\n {\n code: '11502-2', // Laboratory report\n display: 'Laboratory report',\n system: 'http://loinc.org',\n },\n ],\n text: 'Laboratory Results',\n },\n conclusion:\n report.overallStatus === 'NORMAL'\n ? 'All results within normal limits'\n : 'One or more abnormal results detected',\n conclusionCode:\n report.overallStatus === 'ANORMAL'\n ? [\n {\n coding: [\n {\n code: 'A',\n display: 'Abnormal',\n system: 'http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation',\n },\n ],\n },\n ]\n : undefined,\n effectiveDateTime: report.collectionDate,\n id: report.reportId,\n issued: report.createdAt,\n performer: report.laboratoryName ? [{ display: report.laboratoryName }] : undefined,\n resourceType: 'DiagnosticReport',\n result: observationIds.map((id) => ({ reference: `Observation/${id}` })),\n status,\n subject: {\n reference: `Patient/${patientId}`,\n },\n };\n}\n\n/**\n * Convert user profile to FHIR Patient\n * NOTE: CPF is intentionally excluded for privacy (LGPD compliance)\n */\nexport function userProfileToFHIR(profile: UserProfileData): Addressable<FHIRPatient> {\n const nameParts = profile.name.split(' ');\n const given = nameParts.slice(0, -1);\n const family = nameParts[nameParts.length - 1] || '';\n\n return {\n address: profile.address\n ? [\n {\n city: profile.address.city,\n country: profile.address.country || 'BR',\n line: [\n profile.address.street && profile.address.number\n ? `${profile.address.street}, ${profile.address.number}`\n : profile.address.street,\n profile.address.complement,\n ].filter(Boolean) as string[],\n postalCode: profile.address.postalCode,\n state: profile.address.state,\n },\n ]\n : undefined,\n birthDate: profile.birthDate,\n gender: profile.gender,\n id: profile.userId,\n name: [\n {\n family,\n given: given.length > 0 ? given : undefined,\n text: profile.name,\n },\n ],\n resourceType: 'Patient',\n telecom:\n [\n ...(profile.email ? [{ system: 'email' as const, value: profile.email }] : []),\n ...(profile.phone ? [{ system: 'phone' as const, value: profile.phone }] : []),\n ].length > 0\n ? [\n ...(profile.email ? [{ system: 'email' as const, value: profile.email }] : []),\n ...(profile.phone ? [{ system: 'phone' as const, value: profile.phone }] : []),\n ]\n : undefined,\n };\n}\n\n/**\n * Convert complete lab result to FHIR Bundle\n * This is the main function for exporting lab results to FHIR R4 format\n */\nexport function labResultToFHIRBundle(\n report: LabReportData,\n observations: LabObservationData[],\n userProfile: UserProfileData,\n): FHIRBundle {\n const patientId = userProfile.userId;\n\n // Convert observations\n const fhirObservations = observations.map((obs) => {\n const resource = labObservationToFHIR(\n { ...obs, collectionDate: report.collectionDate },\n patientId,\n report.laboratoryName,\n );\n\n return { fullUrl: entryFullUrl(resource), resource };\n });\n\n // Os ids vêm dos recursos já montados, e não de uma segunda montagem da mesma\n // regra. O `DiagnosticReport.result` aponta para eles, e era aqui que a\n // referência se separava do recurso.\n const observationIds = fhirObservations.map((entry) => entry.resource.id);\n\n // Convert report\n const diagnosticReport = labReportToFHIR(report, patientId, observationIds);\n\n // Convert patient\n const fhirPatient = userProfileToFHIR(userProfile);\n\n return {\n entry: [\n { fullUrl: entryFullUrl(fhirPatient), resource: fhirPatient },\n { fullUrl: entryFullUrl(diagnosticReport), resource: diagnosticReport },\n ...fhirObservations,\n ],\n resourceType: 'Bundle',\n type: 'collection',\n };\n}\n"]}
|