@precisa-saude/fhir 0.37.1 → 0.37.2

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@precisa-saude/fhir",
3
- "version": "0.37.1",
3
+ "version": "0.37.2",
4
4
  "description": "Tipos FHIR R4, definições de biomarcadores, faixas de referência e conversores para o ecossistema de saúde brasileiro",
5
5
  "keywords": [
6
6
  "fhir",
@@ -1,276 +0,0 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } }
2
-
3
-
4
- var _chunkOR67NJDZcjs = require('./chunk-OR67NJDZ.cjs');
5
-
6
-
7
- var _chunkDE7NHXIRcjs = require('./chunk-DE7NHXIR.cjs');
8
-
9
-
10
-
11
- var _chunkRWUFK5ANcjs = require('./chunk-RWUFK5AN.cjs');
12
-
13
-
14
-
15
- var _chunkBDS6CM7Fcjs = require('./chunk-BDS6CM7F.cjs');
16
-
17
- // src/bundle-urls.ts
18
- var BUNDLE_BASE_URL = "https://precisa-saude.com.br/fhir";
19
- var entryFullUrl = (resource) => `${BUNDLE_BASE_URL}/${resource.resourceType}/${resource.id}`;
20
-
21
- // src/converter.ts
22
- function interpretationCode(flag) {
23
- switch (flag) {
24
- case "H":
25
- return "H";
26
- // High
27
- case "L":
28
- return "L";
29
- // Low
30
- default:
31
- return "N";
32
- }
33
- }
34
- function interpretationDisplay(flag) {
35
- switch (flag) {
36
- case "H":
37
- return "High";
38
- case "L":
39
- return "Low";
40
- default:
41
- return "Normal";
42
- }
43
- }
44
- var SEX_CODING = {
45
- female: {
46
- code: "female",
47
- display: "Female",
48
- system: "http://hl7.org/fhir/administrative-gender"
49
- },
50
- male: { code: "male", display: "Male", system: "http://hl7.org/fhir/administrative-gender" }
51
- };
52
- var buildReferenceRanges = (observation, quantity) => {
53
- const toRanges = (low, high, sex) => {
54
- if (low === void 0 && high === void 0) return [];
55
- return [
56
- {
57
- ...sex === void 0 ? {} : { appliesTo: [{ coding: [SEX_CODING[sex]] }] },
58
- ...high === void 0 ? {} : { high: quantity(high) },
59
- ...low === void 0 ? {} : { low: quantity(low) }
60
- }
61
- ];
62
- };
63
- if (observation.referenceRanges && observation.referenceRanges.length > 0) {
64
- return observation.referenceRanges.flatMap((r) => toRanges(r.low, r.high, r.appliesTo));
65
- }
66
- const meaning = observation.referenceKind && _chunkDE7NHXIRcjs.referenceRangeMeaning.call(void 0, observation.referenceKind);
67
- return toRanges(observation.referenceMin, observation.referenceMax).map(
68
- (range) => meaning ? { ...range, type: { coding: [meaning] } } : range
69
- );
70
- };
71
- function labObservationToFHIR(observation, patientId, laboratoryName) {
72
- const methodLoinc = observation.methodLoinc && _chunkBDS6CM7Fcjs.methodVariantOf.call(void 0, observation.biomarkerCode, observation.methodLoinc) ? observation.methodLoinc : void 0;
73
- const loincCode = _nullishCoalesce(methodLoinc, () => ( _chunkBDS6CM7Fcjs.codeToLoinc.call(void 0, observation.biomarkerCode)));
74
- const sourceUnit = observation.unit || _chunkRWUFK5ANcjs.getDefaultUnit.call(void 0, observation.biomarkerCode) || observation.unit;
75
- const ucumUnit = _chunkRWUFK5ANcjs.resolveUcum.call(void 0, sourceUnit, observation.biomarkerCode);
76
- const quantity = (value) => ({
77
- ...ucumUnit ? { code: ucumUnit, system: "http://unitsofmeasure.org" } : {},
78
- ...sourceUnit ? { unit: sourceUnit } : {},
79
- value
80
- });
81
- const isQualitative = observation.isQualitative || typeof observation.value === "string";
82
- const fhirObs = {
83
- category: [
84
- {
85
- coding: [
86
- {
87
- code: "laboratory",
88
- display: "Laboratory",
89
- system: "http://terminology.hl7.org/CodeSystem/observation-category"
90
- }
91
- ]
92
- }
93
- ],
94
- code: {
95
- // Sem LOINC, o coding LOINC simplesmente não sai. Antes ia `99999-9`,
96
- // que não é código LOINC nenhum: publicava sob `http://loinc.org` uma
97
- // afirmação falsa, e quem consumisse o bundle confiando no system
98
- // trataria aquilo como código de verdade. Composição corporal, densidade
99
- // óssea e escore de cálcio não têm LOINC, e o certo é a lacuna explícita.
100
- coding: [
101
- ...loincCode ? [
102
- {
103
- code: loincCode,
104
- display: observation.biomarkerName,
105
- system: _chunkOR67NJDZcjs.LOINC_SYSTEM
106
- }
107
- ] : [],
108
- {
109
- code: observation.biomarkerCode,
110
- display: observation.biomarkerName,
111
- system: _chunkOR67NJDZcjs.BIOMARKER_CODE_SYSTEM
112
- }
113
- ],
114
- text: observation.biomarkerName
115
- },
116
- effectiveDateTime: observation.collectionDate,
117
- id: `${observation.reportId}-${observation.biomarkerCode}`,
118
- interpretation: [
119
- {
120
- coding: [
121
- {
122
- code: interpretationCode(observation.flag),
123
- display: interpretationDisplay(observation.flag),
124
- system: "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
125
- }
126
- ]
127
- }
128
- ],
129
- performer: laboratoryName ? [{ display: laboratoryName }] : void 0,
130
- resourceType: "Observation",
131
- status: "final",
132
- subject: {
133
- reference: `Patient/${patientId}`
134
- }
135
- };
136
- if (isQualitative) {
137
- fhirObs.valueString = String(observation.value);
138
- } else {
139
- fhirObs.valueQuantity = quantity(observation.value);
140
- const referenceRange = buildReferenceRanges(observation, quantity);
141
- if (referenceRange.length > 0) fhirObs.referenceRange = referenceRange;
142
- }
143
- return fhirObs;
144
- }
145
- function labReportToFHIR(report, patientId, observationIds) {
146
- let status;
147
- switch (report.processingStatus) {
148
- case "complete":
149
- status = "final";
150
- break;
151
- case "partial":
152
- status = "partial";
153
- break;
154
- case "pending_review":
155
- status = "preliminary";
156
- break;
157
- default:
158
- status = "final";
159
- }
160
- return {
161
- category: [
162
- {
163
- coding: [
164
- {
165
- code: "LAB",
166
- display: "Laboratory",
167
- system: "http://terminology.hl7.org/CodeSystem/v2-0074"
168
- }
169
- ]
170
- }
171
- ],
172
- code: {
173
- coding: [
174
- {
175
- code: "11502-2",
176
- // Laboratory report
177
- display: "Laboratory report",
178
- system: "http://loinc.org"
179
- }
180
- ],
181
- text: "Laboratory Results"
182
- },
183
- conclusion: report.overallStatus === "NORMAL" ? "All results within normal limits" : "One or more abnormal results detected",
184
- conclusionCode: report.overallStatus === "ANORMAL" ? [
185
- {
186
- coding: [
187
- {
188
- code: "A",
189
- display: "Abnormal",
190
- system: "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
191
- }
192
- ]
193
- }
194
- ] : void 0,
195
- effectiveDateTime: report.collectionDate,
196
- id: report.reportId,
197
- issued: report.createdAt,
198
- performer: report.laboratoryName ? [{ display: report.laboratoryName }] : void 0,
199
- resourceType: "DiagnosticReport",
200
- result: observationIds.map((id) => ({ reference: `Observation/${id}` })),
201
- status,
202
- subject: {
203
- reference: `Patient/${patientId}`
204
- }
205
- };
206
- }
207
- function userProfileToFHIR(profile) {
208
- const nameParts = profile.name.split(" ");
209
- const given = nameParts.slice(0, -1);
210
- const family = nameParts[nameParts.length - 1] || "";
211
- return {
212
- address: profile.address ? [
213
- {
214
- city: profile.address.city,
215
- country: profile.address.country || "BR",
216
- line: [
217
- profile.address.street && profile.address.number ? `${profile.address.street}, ${profile.address.number}` : profile.address.street,
218
- profile.address.complement
219
- ].filter(Boolean),
220
- postalCode: profile.address.postalCode,
221
- state: profile.address.state
222
- }
223
- ] : void 0,
224
- birthDate: profile.birthDate,
225
- gender: profile.gender,
226
- id: profile.userId,
227
- name: [
228
- {
229
- family,
230
- given: given.length > 0 ? given : void 0,
231
- text: profile.name
232
- }
233
- ],
234
- resourceType: "Patient",
235
- telecom: [
236
- ...profile.email ? [{ system: "email", value: profile.email }] : [],
237
- ...profile.phone ? [{ system: "phone", value: profile.phone }] : []
238
- ].length > 0 ? [
239
- ...profile.email ? [{ system: "email", value: profile.email }] : [],
240
- ...profile.phone ? [{ system: "phone", value: profile.phone }] : []
241
- ] : void 0
242
- };
243
- }
244
- function labResultToFHIRBundle(report, observations, userProfile) {
245
- const patientId = userProfile.userId;
246
- const fhirObservations = observations.map((obs) => {
247
- const resource = labObservationToFHIR(
248
- { ...obs, collectionDate: report.collectionDate },
249
- patientId,
250
- report.laboratoryName
251
- );
252
- return { fullUrl: entryFullUrl(resource), resource };
253
- });
254
- const observationIds = fhirObservations.map((entry) => entry.resource.id);
255
- const diagnosticReport = labReportToFHIR(report, patientId, observationIds);
256
- const fhirPatient = userProfileToFHIR(userProfile);
257
- return {
258
- entry: [
259
- { fullUrl: entryFullUrl(fhirPatient), resource: fhirPatient },
260
- { fullUrl: entryFullUrl(diagnosticReport), resource: diagnosticReport },
261
- ...fhirObservations
262
- ],
263
- resourceType: "Bundle",
264
- type: "collection"
265
- };
266
- }
267
-
268
-
269
-
270
-
271
-
272
-
273
-
274
-
275
- exports.BUNDLE_BASE_URL = BUNDLE_BASE_URL; exports.entryFullUrl = entryFullUrl; exports.labObservationToFHIR = labObservationToFHIR; exports.labReportToFHIR = labReportToFHIR; exports.userProfileToFHIR = userProfileToFHIR; exports.labResultToFHIRBundle = labResultToFHIRBundle;
276
- //# sourceMappingURL=chunk-A2R65X4X.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-A2R65X4X.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;AACA;AACF,wDAA6B;AAC7B;AACA;ACkBO,IAAM,gBAAA,EAAkB,mCAAA;AAgBxB,IAAM,aAAA,EAAe,CAAC,QAAA,EAAA,GAC3B,CAAA,EAAA;ADhCgC;AACA;AEQc;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;A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FtIkC;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"/home/runner/work/fhir-brasil/fhir-brasil/packages/core/dist/chunk-A2R65X4X.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, methodVariantOf } 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 // O código por método só sai quando é variante declarada do biomarcador. Um\n // `methodLoinc` qualquer viraria afirmação sob `http://loinc.org` que o\n // catálogo não conferiu.\n const methodLoinc =\n observation.methodLoinc && methodVariantOf(observation.biomarkerCode, observation.methodLoinc)\n ? observation.methodLoinc\n : undefined;\n const loincCode = methodLoinc ?? 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"]}
@@ -1,276 +0,0 @@
1
- import {
2
- BIOMARKER_CODE_SYSTEM,
3
- LOINC_SYSTEM
4
- } from "./chunk-A6HR4XDK.js";
5
- import {
6
- referenceRangeMeaning
7
- } from "./chunk-O7SK2YUU.js";
8
- import {
9
- getDefaultUnit,
10
- resolveUcum
11
- } from "./chunk-CZLX33DZ.js";
12
- import {
13
- codeToLoinc,
14
- methodVariantOf
15
- } from "./chunk-YCJUGK6D.js";
16
-
17
- // src/bundle-urls.ts
18
- var BUNDLE_BASE_URL = "https://precisa-saude.com.br/fhir";
19
- var entryFullUrl = (resource) => `${BUNDLE_BASE_URL}/${resource.resourceType}/${resource.id}`;
20
-
21
- // src/converter.ts
22
- function interpretationCode(flag) {
23
- switch (flag) {
24
- case "H":
25
- return "H";
26
- // High
27
- case "L":
28
- return "L";
29
- // Low
30
- default:
31
- return "N";
32
- }
33
- }
34
- function interpretationDisplay(flag) {
35
- switch (flag) {
36
- case "H":
37
- return "High";
38
- case "L":
39
- return "Low";
40
- default:
41
- return "Normal";
42
- }
43
- }
44
- var SEX_CODING = {
45
- female: {
46
- code: "female",
47
- display: "Female",
48
- system: "http://hl7.org/fhir/administrative-gender"
49
- },
50
- male: { code: "male", display: "Male", system: "http://hl7.org/fhir/administrative-gender" }
51
- };
52
- var buildReferenceRanges = (observation, quantity) => {
53
- const toRanges = (low, high, sex) => {
54
- if (low === void 0 && high === void 0) return [];
55
- return [
56
- {
57
- ...sex === void 0 ? {} : { appliesTo: [{ coding: [SEX_CODING[sex]] }] },
58
- ...high === void 0 ? {} : { high: quantity(high) },
59
- ...low === void 0 ? {} : { low: quantity(low) }
60
- }
61
- ];
62
- };
63
- if (observation.referenceRanges && observation.referenceRanges.length > 0) {
64
- return observation.referenceRanges.flatMap((r) => toRanges(r.low, r.high, r.appliesTo));
65
- }
66
- const meaning = observation.referenceKind && referenceRangeMeaning(observation.referenceKind);
67
- return toRanges(observation.referenceMin, observation.referenceMax).map(
68
- (range) => meaning ? { ...range, type: { coding: [meaning] } } : range
69
- );
70
- };
71
- function labObservationToFHIR(observation, patientId, laboratoryName) {
72
- const methodLoinc = observation.methodLoinc && methodVariantOf(observation.biomarkerCode, observation.methodLoinc) ? observation.methodLoinc : void 0;
73
- const loincCode = methodLoinc ?? codeToLoinc(observation.biomarkerCode);
74
- const sourceUnit = observation.unit || getDefaultUnit(observation.biomarkerCode) || observation.unit;
75
- const ucumUnit = resolveUcum(sourceUnit, observation.biomarkerCode);
76
- const quantity = (value) => ({
77
- ...ucumUnit ? { code: ucumUnit, system: "http://unitsofmeasure.org" } : {},
78
- ...sourceUnit ? { unit: sourceUnit } : {},
79
- value
80
- });
81
- const isQualitative = observation.isQualitative || typeof observation.value === "string";
82
- const fhirObs = {
83
- category: [
84
- {
85
- coding: [
86
- {
87
- code: "laboratory",
88
- display: "Laboratory",
89
- system: "http://terminology.hl7.org/CodeSystem/observation-category"
90
- }
91
- ]
92
- }
93
- ],
94
- code: {
95
- // Sem LOINC, o coding LOINC simplesmente não sai. Antes ia `99999-9`,
96
- // que não é código LOINC nenhum: publicava sob `http://loinc.org` uma
97
- // afirmação falsa, e quem consumisse o bundle confiando no system
98
- // trataria aquilo como código de verdade. Composição corporal, densidade
99
- // óssea e escore de cálcio não têm LOINC, e o certo é a lacuna explícita.
100
- coding: [
101
- ...loincCode ? [
102
- {
103
- code: loincCode,
104
- display: observation.biomarkerName,
105
- system: LOINC_SYSTEM
106
- }
107
- ] : [],
108
- {
109
- code: observation.biomarkerCode,
110
- display: observation.biomarkerName,
111
- system: BIOMARKER_CODE_SYSTEM
112
- }
113
- ],
114
- text: observation.biomarkerName
115
- },
116
- effectiveDateTime: observation.collectionDate,
117
- id: `${observation.reportId}-${observation.biomarkerCode}`,
118
- interpretation: [
119
- {
120
- coding: [
121
- {
122
- code: interpretationCode(observation.flag),
123
- display: interpretationDisplay(observation.flag),
124
- system: "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
125
- }
126
- ]
127
- }
128
- ],
129
- performer: laboratoryName ? [{ display: laboratoryName }] : void 0,
130
- resourceType: "Observation",
131
- status: "final",
132
- subject: {
133
- reference: `Patient/${patientId}`
134
- }
135
- };
136
- if (isQualitative) {
137
- fhirObs.valueString = String(observation.value);
138
- } else {
139
- fhirObs.valueQuantity = quantity(observation.value);
140
- const referenceRange = buildReferenceRanges(observation, quantity);
141
- if (referenceRange.length > 0) fhirObs.referenceRange = referenceRange;
142
- }
143
- return fhirObs;
144
- }
145
- function labReportToFHIR(report, patientId, observationIds) {
146
- let status;
147
- switch (report.processingStatus) {
148
- case "complete":
149
- status = "final";
150
- break;
151
- case "partial":
152
- status = "partial";
153
- break;
154
- case "pending_review":
155
- status = "preliminary";
156
- break;
157
- default:
158
- status = "final";
159
- }
160
- return {
161
- category: [
162
- {
163
- coding: [
164
- {
165
- code: "LAB",
166
- display: "Laboratory",
167
- system: "http://terminology.hl7.org/CodeSystem/v2-0074"
168
- }
169
- ]
170
- }
171
- ],
172
- code: {
173
- coding: [
174
- {
175
- code: "11502-2",
176
- // Laboratory report
177
- display: "Laboratory report",
178
- system: "http://loinc.org"
179
- }
180
- ],
181
- text: "Laboratory Results"
182
- },
183
- conclusion: report.overallStatus === "NORMAL" ? "All results within normal limits" : "One or more abnormal results detected",
184
- conclusionCode: report.overallStatus === "ANORMAL" ? [
185
- {
186
- coding: [
187
- {
188
- code: "A",
189
- display: "Abnormal",
190
- system: "http://terminology.hl7.org/CodeSystem/v3-ObservationInterpretation"
191
- }
192
- ]
193
- }
194
- ] : void 0,
195
- effectiveDateTime: report.collectionDate,
196
- id: report.reportId,
197
- issued: report.createdAt,
198
- performer: report.laboratoryName ? [{ display: report.laboratoryName }] : void 0,
199
- resourceType: "DiagnosticReport",
200
- result: observationIds.map((id) => ({ reference: `Observation/${id}` })),
201
- status,
202
- subject: {
203
- reference: `Patient/${patientId}`
204
- }
205
- };
206
- }
207
- function userProfileToFHIR(profile) {
208
- const nameParts = profile.name.split(" ");
209
- const given = nameParts.slice(0, -1);
210
- const family = nameParts[nameParts.length - 1] || "";
211
- return {
212
- address: profile.address ? [
213
- {
214
- city: profile.address.city,
215
- country: profile.address.country || "BR",
216
- line: [
217
- profile.address.street && profile.address.number ? `${profile.address.street}, ${profile.address.number}` : profile.address.street,
218
- profile.address.complement
219
- ].filter(Boolean),
220
- postalCode: profile.address.postalCode,
221
- state: profile.address.state
222
- }
223
- ] : void 0,
224
- birthDate: profile.birthDate,
225
- gender: profile.gender,
226
- id: profile.userId,
227
- name: [
228
- {
229
- family,
230
- given: given.length > 0 ? given : void 0,
231
- text: profile.name
232
- }
233
- ],
234
- resourceType: "Patient",
235
- telecom: [
236
- ...profile.email ? [{ system: "email", value: profile.email }] : [],
237
- ...profile.phone ? [{ system: "phone", value: profile.phone }] : []
238
- ].length > 0 ? [
239
- ...profile.email ? [{ system: "email", value: profile.email }] : [],
240
- ...profile.phone ? [{ system: "phone", value: profile.phone }] : []
241
- ] : void 0
242
- };
243
- }
244
- function labResultToFHIRBundle(report, observations, userProfile) {
245
- const patientId = userProfile.userId;
246
- const fhirObservations = observations.map((obs) => {
247
- const resource = labObservationToFHIR(
248
- { ...obs, collectionDate: report.collectionDate },
249
- patientId,
250
- report.laboratoryName
251
- );
252
- return { fullUrl: entryFullUrl(resource), resource };
253
- });
254
- const observationIds = fhirObservations.map((entry) => entry.resource.id);
255
- const diagnosticReport = labReportToFHIR(report, patientId, observationIds);
256
- const fhirPatient = userProfileToFHIR(userProfile);
257
- return {
258
- entry: [
259
- { fullUrl: entryFullUrl(fhirPatient), resource: fhirPatient },
260
- { fullUrl: entryFullUrl(diagnosticReport), resource: diagnosticReport },
261
- ...fhirObservations
262
- ],
263
- resourceType: "Bundle",
264
- type: "collection"
265
- };
266
- }
267
-
268
- export {
269
- BUNDLE_BASE_URL,
270
- entryFullUrl,
271
- labObservationToFHIR,
272
- labReportToFHIR,
273
- userProfileToFHIR,
274
- labResultToFHIRBundle
275
- };
276
- //# sourceMappingURL=chunk-I6FCFMAO.js.map
@@ -1 +0,0 @@
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, methodVariantOf } 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 // O código por método só sai quando é variante declarada do biomarcador. Um\n // `methodLoinc` qualquer viraria afirmação sob `http://loinc.org` que o\n // catálogo não conferiu.\n const methodLoinc =\n observation.methodLoinc && methodVariantOf(observation.biomarkerCode, observation.methodLoinc)\n ? observation.methodLoinc\n : undefined;\n const loincCode = methodLoinc ?? 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;AAAA,MACL;AAAA,QACE,GAAI,QAAQ,SAAY,CAAC,IAAI,EAAE,WAAW,CAAC,EAAE,QAAQ,CAAC,WAAW,GAAG,CAAC,EAAE,CAAC,EAAE;AAAA,QAC1E,GAAI,SAAS,SAAY,CAAC,IAAI,EAAE,MAAM,SAAS,IAAI,EAAE;AAAA,QACrD,GAAI,QAAQ,SAAY,CAAC,IAAI,EAAE,KAAK,SAAS,GAAG,EAAE;AAAA,MACpD;AAAA,IACF;AAAA,EACF;AAUA,MAAI,YAAY,mBAAmB,YAAY,gBAAgB,SA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