This repository is currently being migrated. It's locked while the migration is in progress.
-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathlab_or_test_adapter.rb
More file actions
795 lines (669 loc) · 30.8 KB
/
lab_or_test_adapter.rb
File metadata and controls
795 lines (669 loc) · 30.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
# frozen_string_literal: true
require_relative '../models/lab_or_test'
require_relative '../reference_range_formatter'
require_relative '../facility_service'
require_relative '../source_constants'
require_relative 'date_normalizer'
require_relative 'fhir_helpers'
require_relative 'facility_name_resolver'
require 'medical_records/medical_records_log'
module UnifiedHealthData
module Adapters
class LabOrTestAdapter # rubocop:disable Metrics/ClassLength
include DateNormalizer
include FhirHelpers
ALLOWED_STATUSES = %w[final amended corrected appended].freeze
VISTA_HOSTNAME_PATTERN = /\.MED\.VA\.GOV$/i
VA_STATION_OID = 'urn:oid:2.16.840.1.113883.4.349'
LABS = MedicalRecords::MedicalRecordsLog::LABS_AND_TESTS
# @param mr_log [MedicalRecords::MedicalRecordsLog, nil] Structured logger (nil = Rails.logger fallback)
def initialize(mr_log: nil)
@mr_log = mr_log
end
# HL7 v2-0074 diagnostic service section codes and LOINC codes to user-friendly display names
TEST_CODE_DISPLAY_MAP = {
'CH' => 'Chemistry and hematology',
'MI' => 'Microbiology',
'MB' => 'Microbiology',
'SP' => 'Surgical Pathology',
'CY' => 'Cytology',
'EM' => 'Electron Microscopy',
'LP29684-5' => 'Radiology'
}.freeze
#
# Interpretation code map based on https://terminology.hl7.org/3.1.0/CodeSystem-v3-ObservationInterpretation.html
#
INTERPRETATION_MAP = {
'CAR' => 'Carrier',
'CARRIER' => 'Carrier',
'<' => 'Off scale low',
'>' => 'Off scale high',
'A' => 'Abnormal',
'AA' => 'Critical abnormal',
'AC' => 'Anti-complementary substances present',
'B' => 'Better',
'D' => 'Significant change down',
'DET' => 'Detected',
'E' => 'Equivocal',
'EX' => 'Outside threshold',
'EXP' => 'Expected',
'H' => 'High',
'H*' => 'Critical high',
'HH' => 'Critical high',
'HU' => 'Significantly high',
'H>' => 'Significantly high',
'HM' => 'Hold for Medical Review',
'HX' => 'Above high threshold',
'I' => 'Intermediate',
'IE' => 'Insufficient evidence',
'IND' => 'Indeterminate',
'L' => 'Low',
'L*' => 'Critical low',
'LL' => 'Critical low',
'LU' => 'Significantly low',
'L<' => 'Significantly low',
'LX' => 'Below low threshold',
'MS' => 'Moderately susceptible',
'N' => 'Normal',
'NCL' => 'No CLSI defined breakpoint',
'ND' => 'Not detected',
'NEG' => 'Negative',
'NR' => 'Non-reactive',
'NS' => 'Non-susceptible',
'OBX' => 'Interpretation qualifiers in separate OBX segments',
'POS' => 'Positive',
'QCF' => 'Quality control failure',
'R' => 'Resistant',
'RR' => 'Reactive',
'S' => 'Susceptible',
'SDD' => 'Susceptible-dose dependent',
'SYN-R' => 'Synergy - resistant',
'SYN-S' => 'Synergy - susceptible',
'TOX' => 'Cytotoxic substance present',
'U' => 'Significant change up',
'UNE' => 'Unexpected',
'VS' => 'Very susceptible',
'W' => 'Worse',
'WR' => 'Weakly reactive'
}.freeze
def parse_labs(records)
return [] if records.blank?
filtered = records.select do |record|
record['resource'] && record['resource']['resourceType'] == 'DiagnosticReport'
end
filtered.filter_map do |record|
parse_single_record(record)
rescue Common::Exceptions::BaseError
raise
rescue => e
log_record_parse_failure(record, e)
nil
end
end
# Public method to extract station number from a record's contained resources.
# Used by Service layer for cache pre-warming.
#
# @param record [Hash] A UHD record with 'resource' > 'contained'
# @return [String, nil] Station number or nil if not found
def extract_station_number_from_record(record)
return nil if record.nil?
contained = record.dig('resource', 'contained')
extract_station_number(contained)
end
private
def parse_single_record(record)
return nil if record.nil? || record['resource'].nil?
# Filter out DiagnosticReports with disallowed status
unless allowed_status?(record['resource']['status'])
log_filtered_diagnostic_report(record, 'disallowed_status')
return nil
end
contained = record['resource']['contained']
code = get_code(record)
encoded_data = get_encoded_data(record['resource'])
observations = get_observations(record)
# Log warnings before filtering out records
log_warnings(record, encoded_data, observations)
# Return nil if there's no code, and if there's no encoded data AND no valid observations
unless code && (encoded_data.present? || observations.any?)
log_filtered_diagnostic_report(record, 'no_valid_data')
return nil
end
build_lab_or_test(record, code, encoded_data, observations, contained)
end
def allowed_status?(status)
ALLOWED_STATUSES.include?(status)
end
# Dual-path logging: structured mr_log when available, Rails.logger fallback otherwise.
def log_adapter(level, structured_opts, fallback_message, fallback_opts = {})
if @mr_log
@mr_log.public_send(level, **structured_opts)
else
Rails.logger.public_send(level, fallback_message, fallback_opts.presence)
end
end
def build_lab_or_test(record, code, encoded_data, observations, contained) # rubocop:disable Metrics/MethodLength
resource = record['resource']
date_completed_value, facility_timezone = resolve_date_and_timezone(resource, contained)
UnifiedHealthData::LabOrTest.new(
id: resource['id'],
type: resource['resourceType'],
display: format_display(resource, record['source']),
test_code: code,
test_code_display: get_test_code_display(record, code),
date_completed: date_completed_value,
sort_date: normalize_date_for_sorting(date_completed_value),
sample_tested: get_sample_tested(resource, contained),
encoded_data:,
location: get_location(record),
ordered_by: get_ordered_by(record),
comments: extract_comments(record),
observations:,
body_site: get_body_site(resource, contained),
status: resource['status'],
source: record['source'],
facility_timezone:
)
end # rubocop:enable Metrics/MethodLength
# Resolves date_completed and facility_timezone by extracting station number
# and converting UTC to facility local time when possible
def resolve_date_and_timezone(resource, contained)
raw_date = get_date_completed(resource)
station_number = extract_station_number(contained)
facility_timezone = get_facility_timezone(station_number)
date_completed = convert_to_facility_time(raw_date, facility_timezone)
[date_completed, facility_timezone]
end
def log_warnings(record, encoded_data, observations)
log_final_status_warning(record, record['resource']['status'], encoded_data, observations)
log_missing_date_warning(record)
end
def log_filtered_diagnostic_report(record, reason)
resource = record['resource']
log_adapter(
:info,
{ resource: LABS, action: 'filter', report_id: resource['id'],
status: resource['status'], reason:, filtering: true },
"Filtered DiagnosticReport: id=#{resource['id']}, status=#{resource['status']}, reason=#{reason}",
{ service: 'unified_health_data', filtering: true }
)
StatsD.increment('unified_health_data.lab_or_test.filtered_diagnostic_report',
tags: ["reason:#{reason}"])
end
def log_filtered_observations(record, filtered_count, total_count)
resource = record['resource']
log_adapter(
:info,
{ resource: LABS, action: 'filter_observations', report_id: resource['id'],
filtered: filtered_count, total: total_count, filtering: true },
"Filtered #{filtered_count}/#{total_count} Observations from DiagnosticReport #{resource['id']}",
{ service: 'unified_health_data', filtering: true }
)
# Increment the counter once per DiagnosticReport that has filtered observations
StatsD.increment('unified_health_data.lab_or_test.filtered_observations')
end
# Logs when an individual record fails to parse. Isolates one bad record from
# killing the entire batch so the veteran still sees the rest of their results.
def log_record_parse_failure(record, error)
report_id = record.dig('resource', 'id')
log_adapter(
:error,
{ resource: LABS, action: 'parse', anomaly: 'record_parse_failure',
report_id:, error_class: error.class.name, error_message: error.message },
"Failed to parse DiagnosticReport #{report_id}: #{error.class} - #{error.message}",
{ service: 'unified_health_data' }
)
StatsD.increment('unified_health_data.lab_or_test.parse_failure')
end
# Logs when an individual observation within a DiagnosticReport fails to parse.
# Isolates one bad observation so the rest of the record's observations are still returned.
def log_observation_parse_failure(record, obs, error)
report_id = record.dig('resource', 'id')
observation_id = obs['id']
log_adapter(
:error,
{ resource: LABS, action: 'parse', anomaly: 'observation_parse_failure',
report_id:, observation_id:, error_class: error.class.name, error_message: error.message },
"Failed to parse Observation #{observation_id} in DiagnosticReport #{report_id}: " \
"#{error.class} - #{error.message}",
{ service: 'unified_health_data' }
)
StatsD.increment('unified_health_data.lab_or_test.observation_parse_failure')
end
def log_final_status_warning(record, status, encoded_data, observations)
return unless status == 'final' && encoded_data.blank? && observations.blank?
report_id = record['resource']['id']
if @mr_log
@mr_log.warn(resource: LABS, action: 'parse', anomaly: 'final_status_empty_data', report_id:)
else
patient_ref = record['resource']&.dig('subject', 'reference')
patient_last_four = patient_ref&.split('/')&.last&.last(4) || 'unknown'
Rails.logger.warn(
"DiagnosticReport #{report_id} has status 'final' but is missing " \
"both encoded data and observations (Patient: #{patient_last_four})",
{ service: 'unified_health_data' }
)
end
StatsD.increment('unified_health_data.lab_or_test.final_status_empty_data')
end
def log_missing_date_warning(record)
resource = record['resource']
effective_date_time = resource['effectiveDateTime']
effective_period = resource['effectivePeriod']
detail = if effective_date_time.blank? && effective_period.blank?
'missing effectiveDateTime and effectivePeriod'
elsif effective_period.present? && effective_period['start'].blank?
'missing effectivePeriod.start'
end
return unless detail
log_adapter(
:warn,
{ resource: LABS, action: 'parse', anomaly: 'missing_date', report_id: resource['id'], detail: },
"DiagnosticReport #{resource['id']} is #{detail}",
{ service: 'unified_health_data' }
)
end
def get_location(record)
contained = record.dig('resource', 'contained')
return nil if contained.nil?
performers = record.dig('resource', 'performer') || []
performer_ref_ids = performers.map { |p| get_reference_id(p['reference']) }.compact
match = contained.find do |r|
%w[Organization Location].include?(r['resourceType']) &&
performer_ref_ids.include?(r['id'])
end
name = match&.dig('name')
if name.present? && match['resourceType'] == 'Organization' && name.match?(VISTA_HOSTNAME_PATTERN)
return resolve_hostname_location(match)
end
return name if name.present?
# Fallback: first Organization or Location in contained order.
# VistA records typically use Organization; OH records use Location.
contained.find { |r| %w[Organization Location].include?(r['resourceType']) }&.dig('name')
end
def resolve_hostname_location(organization)
identifier = organization&.dig('identifier')&.find { |id| id['system'] == VA_STATION_OID }
station_number = identifier&.dig('value')
return nil if station_number.blank?
facility_name_resolver.lookup(station_number)
rescue => e
Rails.logger.warn(
'Failed to resolve facility name for hostname location ' \
"(organization_id=#{organization['id']}, station_number=#{station_number}, " \
"error_class=#{e.class}): #{e.message}",
{
service: 'unified_health_data',
organization_id: organization['id'],
station_number:,
error_class: e.class.to_s
}
)
nil
end
def facility_name_resolver
@facility_name_resolver ||= UnifiedHealthData::Adapters::FacilityNameResolver.new
end
def get_code(record)
return nil if record['resource']['category'].blank?
coding = record['resource']['category'].find do |category|
category['coding'].present? && category['coding'][0]['code'] != 'LAB'
end
coding ? coding['coding'][0]['code'] : nil
end
# Normalize code for display mapping only (preserves raw code in test_code field)
# Extracts 2-letter code from VistA URN format: "urn:va:lab-category:MI" -> "MI"
def normalize_code_for_display(code)
return code if code.nil?
code.match(/urn:va:lab-category:(\w+)/)&.captures&.first || code
end
# Get the display name for a test code with fallback chain:
# 1. Check TEST_CODE_DISPLAY_MAP (using normalized code)
# 2. Fall back to category.coding.display from the FHIR data
# 3. Fall back to category.text from the FHIR data
# 4. Final fallback: the normalized code itself
def get_test_code_display(record, code)
normalized_code = normalize_code_for_display(code)
# First, check our explicit mapping
return TEST_CODE_DISPLAY_MAP[normalized_code] if TEST_CODE_DISPLAY_MAP.key?(normalized_code)
# Fall back to display/text from the category coding in FHIR data
category_display = get_category_display(record)
return category_display if category_display.present?
# Final fallback: use the normalized code
normalized_code
end
# Extract display or text from the category that has the test code
def get_category_display(record)
return nil if record['resource']['category'].blank?
category = record['resource']['category'].find do |cat|
cat['coding'].present? && cat['coding'][0]['code'] != 'LAB'
end
return nil unless category
# Try coding.display first, then category.text
extract_codeable_concept_display(category, prefer: :coding)
end
def extract_comments(record)
resource = record['resource']
comments = []
# Extract comments from DiagnosticReport extensions (VistA labComment extensions)
if resource['extension'].present?
extension_comments = resource['extension'].filter_map { |ext| ext['valueString'] }
comments.concat(extension_comments)
end
# Extract comments from ServiceRequest.note[].text in contained resources (Oracle Health)
if resource['basedOn'].present? && resource['contained'].present?
resource['basedOn'].each do |based_on|
service_request = resource['contained'].find do |r|
r['resourceType'] == 'ServiceRequest' && r['id'] == get_reference_id(based_on['reference'])
end
next unless service_request&.dig('note').is_a?(Array)
note_comments = service_request['note'].filter_map { |note| note['text'] }
comments.concat(note_comments)
end
end
comments.presence
end
def get_body_site(resource, contained)
return '' unless resource['basedOn']
return '' if contained.nil?
body_sites = []
resource['basedOn'].each do |based_on|
service_request = contained.find do |r|
r['resourceType'] == 'ServiceRequest' && r['id'] == get_reference_id(based_on['reference'])
end
next unless service_request&.dig('bodySite')
service_request['bodySite'].each do |body_site|
# Prefer coding display (VistA uses this), fall back to CodeableConcept text (OH uses this)
display = extract_codeable_concept_display(body_site, prefer: :coding)
body_sites << display if display.present?
end
end
body_sites.join(', ').strip
end
def get_sample_tested(record, contained)
return '' unless record['specimen']
return '' if contained.nil?
specimen_references = if record['specimen'].is_a?(Hash)
[get_reference_id(record['specimen']['reference'])]
elsif record['specimen'].is_a?(Array)
record['specimen'].map { |specimen| get_reference_id(specimen['reference']) }
end
specimens =
specimen_references.map do |reference|
specimen_object = contained.find do |resource|
resource['resourceType'] == 'Specimen' && resource['id'] == reference
end
specimen_object&.dig('type', 'text')
end
specimens.compact.join(', ').strip
end
def get_observations(record)
return [] if record['resource']['contained'].nil?
all_observations = record['resource']['contained'].select do |resource|
resource['resourceType'] == 'Observation'
end
valid_observations, filtered_count = parse_valid_observations(all_observations, record)
# Log and track filtered observations
log_filtered_observations(record, filtered_count, all_observations.size) if filtered_count.positive?
valid_observations
end
def parse_valid_observations(all_observations, record)
filtered_count = 0
valid = all_observations.filter_map do |obs|
unless allowed_status?(obs['status'])
filtered_count += 1
next
end
begin
build_observation(obs, record['resource']['contained'])
rescue Common::Exceptions::BaseError
raise
rescue => e
log_observation_parse_failure(record, obs, e)
nil
end
end
[valid, filtered_count]
end
def build_observation(obs, contained)
sample_tested = get_sample_tested(obs, contained)
body_site = get_body_site(obs, contained)
UnifiedHealthData::Observation.new(
test_code: obs['code']['text'],
value: format_observation_value(obs),
reference_range: UnifiedHealthData::ReferenceRangeFormatter.format(obs),
status: obs['status'],
interpretation: extract_interpretation(obs),
comments: obs['note']&.map { |note| note['text'] }&.compact || [],
sample_tested:,
body_site:
)
end
def extract_interpretation(obs)
interpretations = obs['interpretation']
return nil if interpretations.blank?
fallback_text = nil
fallback_code = nil
interpretations.each do |interp|
if interp['coding'].present?
hl7_coding = interp['coding'].find do |coding|
coding['system']&.include?('v3-ObservationInterpretation') && coding['code'].present?
end
if hl7_coding
# Priority 1: Mapped human-friendly display from INTERPRETATION_MAP
mapped = INTERPRETATION_MAP[hl7_coding['code']]
return mapped if mapped.present?
# Capture raw code as absolute last resort fallback
fallback_code ||= hl7_coding['code']
end
end
# Priority 2: text or coding.display from the CodeableConcept
fallback_text ||= extract_codeable_concept_display(interp)
end
# Prefer human-readable text/display over raw code
fallback_text || fallback_code
end
def format_observation_value(obs)
type, text = if obs['valueQuantity']
['quantity', format_quantity_value(obs['valueQuantity'])]
elsif obs['valueCodeableConcept']
['codeable-concept', obs['valueCodeableConcept']['text']]
elsif obs['valueString']
['string', obs['valueString']]
elsif obs['valueDateTime']
['date-time', obs['valueDateTime']]
elsif obs['valueAttachment']
log_adapter(
:error,
{ resource: LABS, action: 'parse', anomaly: 'unsupported_value_type',
observation_id: obs['id'], value_type: 'Attachment' },
{ message: "Observation with ID #{obs['id']} has unsupported value type: Attachment" }
)
raise Common::Exceptions::NotImplemented
else
[nil, nil]
end
{ text:, type: }
end
def format_quantity_value(value_quantity)
value = value_quantity['value']
unit = value_quantity['unit']
comparator = value_quantity['comparator']
result_text = ''
result_text += comparator.to_s if comparator.present?
result_text += value.to_s
result_text += " #{unit}" if unit.present?
result_text
end
def get_ordered_by(record)
contained = record.dig('resource', 'contained')
return nil if contained.nil?
service_request = contained.find { |r| r['resourceType'] == 'ServiceRequest' }
requester = service_request&.dig('requester')
return nil unless requester
requester_id = get_reference_id(requester['reference'])
practitioner = contained.find do |r|
r['resourceType'] == 'Practitioner' && r['id'] == requester_id
end
if practitioner
name = practitioner['name'].first
"#{name['given'].join(' ')} #{name['family']}"
else
# OH records may include a display name on the requester when the Practitioner
# is not embedded in the contained array
requester['display']
end
end
def get_reference_id(reference)
return nil if reference.blank?
# Some of the VistA data doesn't use the full reference format, and instead just has the ID,
# so we need to handle both cases
return reference if reference&.exclude?('/')
reference.split('/').last
end
def format_display(resource, source = nil)
# Check presentedForm title first (e.g., radiology reports) — applies to all sources
title = resource['presentedForm']
&.find { |form| form['contentType'] == 'text/plain' }
&.dig('title')
return title if title.present?
if source == UnifiedHealthData::SourceConstants::ORACLE_HEALTH
format_display_oracle_health(resource)
else
format_display_vista(resource)
end
end
def format_display_oracle_health(resource)
# 1. ServiceRequest.code.text
service_request = resource['contained']&.find { |r| r['resourceType'] == 'ServiceRequest' }
service_request_code_text = service_request&.dig('code', 'text')
return service_request_code_text if service_request_code_text.present?
# 2. First category.coding.display
resource['category']&.each do |cat|
coding_display = first_coding_display(cat)
return coding_display if coding_display.present?
end
# 3. Fall back to code.text
code_display = extract_codeable_concept_display(resource['code'])
return code_display if code_display.present?
''
end
def format_display_vista(resource)
# Top-level code.text, then first found code.coding.display
code_display = extract_codeable_concept_display(resource['code'])
return code_display if code_display.present?
# Fallback to contained ServiceRequest
service_request = resource['contained']&.find { |r| r['resourceType'] == 'ServiceRequest' }
service_request&.dig('code', 'text').presence ||
service_request&.dig('category', 0, 'coding', 0, 'display').presence ||
''
end
def get_encoded_data(resource)
return '' unless resource['presentedForm']&.any?
# Find the presentedForm item with contentType 'text/plain'
presented_form = resource['presentedForm'].find { |form| form['contentType'] == 'text/plain' }
return '' unless presented_form
# Handle standard data field or extensions indicating data-absent-reason
# Return empty string when data is absent (either with data-absent-reason extension or missing)
presented_form['data'] || ''
end
def get_date_completed(resource)
# Handle both effectiveDateTime and effectivePeriod formats
if resource['effectiveDateTime']
resource['effectiveDateTime']
elsif resource['effectivePeriod']&.dig('start')
resource['effectivePeriod']['start']
# Fallback to report's creation date if no other dates available
elsif resource['presentedForm']
resource['presentedForm'].find { |form| form['contentType'] == 'text/plain' }&.dig('creation')
end
end
# Extracts station number from contained resources using multiple fallback strategies
# Fallback chain:
# 1. Practitioner SN=XXX format (most explicit, Oracle Health)
# 2. Practitioner plain 3-digit number with "OTHER" type (Oracle Health)
# 3. Organization with VA OID system (VistA data via UHD)
#
# @param contained [Array<Hash>] Array of contained FHIR resources
# @return [String, nil] Station number (e.g., '668') or nil if not found
def extract_station_number(contained)
return nil if contained.blank?
# Try Practitioner identifiers first (Oracle Health data)
station_number = extract_station_from_practitioner(contained)
return station_number if station_number.present?
# Fallback: Try Organization identifiers (VistA data via UHD)
extract_station_from_organization(contained)
end
# Extracts station number from Practitioner identifiers
# Used primarily for Oracle Health data
# Priority: SN=XXX format > plain 3-digit with OTHER type
#
# @param contained [Array<Hash>] Array of contained FHIR resources
# @return [String, nil] Station number or nil if not found
def extract_station_from_practitioner(contained)
practitioner = contained.find { |r| r['resourceType'] == 'Practitioner' }
return nil unless practitioner&.dig('identifier')
identifiers = practitioner['identifier']
# Priority 1: SN=XXX format (most explicit)
sn_identifier = identifiers.find { |i| (val = i['value']).present? && val.start_with?('SN=') }
return sn_identifier['value'].sub('SN=', '') if sn_identifier
# Priority 2: Station number with "OTHER" type (3 digits, optionally with letter suffix like 668A, 668GC)
plain_identifier = identifiers.find do |i|
(val = i['value']).present? && i.dig('type', 'text') == 'OTHER' && val.match?(/^\d{3}[A-Z]{0,2}$/i)
end
plain_identifier&.dig('value')
end
# Extracts station number from Organization identifiers
# Used primarily for VistA data coming through UHD
# Looks for identifiers with the VA OID system (urn:oid:2.16.840.1.113883.4.349)
#
# @param contained [Array<Hash>] Array of contained FHIR resources
# @return [String, nil] Station number or nil if not found
def extract_station_from_organization(contained)
organization = contained.find { |r| r['resourceType'] == 'Organization' }
return nil unless organization&.dig('identifier')
organization['identifier'].each do |identifier|
system = identifier['system']
value = identifier['value']
# VA OID system identifier contains station number
# Example: {"system": "urn:oid:2.16.840.1.113883.4.349", "value": "989"}
next unless system.to_s.include?('2.16.840.1.113883.4.349') && value.present?
return value
end
nil
end
# Gets the facility timezone using the UHD FacilityService
#
# @param station_number [String] The station number (e.g., '668')
# @return [String, nil] IANA timezone ID (e.g., 'America/Los_Angeles') or nil if not found
def get_facility_timezone(station_number)
return nil if station_number.blank?
facility_service.get_facility_timezone(station_number)
end
def facility_service
@facility_service ||= UnifiedHealthData::FacilityService.new
end
# Converts a UTC datetime string to facility local time
#
# @param date_string [String] ISO 8601 datetime string (e.g., '2023-11-06T18:32:00+00:00')
# @param timezone [String] IANA timezone ID (e.g., 'America/Los_Angeles')
# @return [String] ISO 8601 datetime string in facility local time, or original if conversion fails
def convert_to_facility_time(date_string, timezone)
return date_string if date_string.blank? || timezone.blank?
begin
# Parse the datetime and convert to the facility timezone
parsed_time = DateTime.parse(date_string).to_time.utc
local_time = parsed_time.in_time_zone(timezone)
local_time.iso8601
rescue ArgumentError, TypeError, TZInfo::InvalidTimezoneIdentifier, TZInfo::UnknownTimezone => e
log_adapter(
:warn,
{ resource: LABS, action: 'timezone_conversion', error_message: e.message, date_string:, timezone: },
"Failed to convert time to facility timezone: #{e.message}",
{ service: 'unified_health_data', date_string:, timezone: }
)
date_string
end
end
end
end
end