Module: DaVinciPASTestKit::MockServer

Included in:
ClientSuite
Defined in:
lib/davinci_pas_test_kit/mock_server.rb

Overview

Serve responses to PAS requests

Note that there are numerous expected validation issues that can safely be ignored. See here for full list: hl7.org/fhir/us/davinci-pas/STU2/qa.html#suppressed

Instance Method Summary collapse

Instance Method Details

#absolute_reference(ref, entries, root_url) ⇒ Object



189
190
191
192
193
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 189

def absolute_reference(ref, entries, root_url)
  url = find_matching_entry(ref&.reference, entries, root_url)&.fullUrl
  ref.reference = url if url
  ref
end

#base_url(url) ⇒ Object

Drop the last two segments of a URL, i.e. the resource type and ID of a FHIR resource e.g. example.org/fhir/Patient/123 -> example.org/fhir



161
162
163
164
165
166
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 161

def base_url(url)
  return unless url&.start_with?('http://', 'https://')

  # Drop everything after the second to last '/', ignoring a trailing slash
  url.sub(%r{/[^/]*/[^/]*(/)?\z}, '')
end

#claim_response(request, test = nil, test_result = nil) ⇒ Object



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
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 15

def claim_response(request, test = nil, test_result = nil)
  request.status = 200
  request.response_headers = { 'Content-Type': 'application/json' }

  user_inputted_response = UserInputResponse.user_inputted_response(test, test_result)
  if test.present? && test_result.present? && user_inputted_response.present?
    request.response_body = user_inputted_response
    return
  end

  operation = request&.url&.split('$')&.last
  req_bundle = FHIR.from_contents(request&.request_body)
  claim_entry = req_bundle&.entry&.find { |e| e&.resource&.resourceType == 'Claim' }
  claim_full_url = claim_entry&.fullUrl
  if claim_entry.blank? || claim_full_url.blank?
    handle_missing_required_elements(claim_entry, request)
    return
  end

  root_url = base_url(claim_full_url)
  claim_response = mock_claim_response(claim_entry.resource, req_bundle, operation, root_url)

  res_bundle = FHIR::Bundle.new(
    id: SecureRandom.uuid,
    meta: FHIR::Meta.new(profile: if operation == 'submit'
                                    'http://hl7.org/fhir/us/davinci-pas/StructureDefinition/profile-pas-response-bundle'
                                  else
                                    'http://hl7.org/fhir/us/davinci-pas/StructureDefinition/profile-pas-inquiry-response-bundle'
                                  end),
    timestamp: Time.now.utc.iso8601,
    type: 'collection',
    entry: [
      FHIR::Bundle::Entry.new(fullUrl: "urn:uuid:#{claim_response.id}",
                              resource: claim_response)
    ]
  )

  res_bundle.entry.concat(referenced_entities(claim_response, req_bundle.entry, root_url))

  request.response_body = res_bundle.to_json
  request.status = 200
  request.response_headers = { 'Content-Type': 'application/json' }
end

#extract_bearer_token(request) ⇒ Object

Header expected to be a bearer token of the form “Bearer: <token>”



136
137
138
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 136

def extract_bearer_token(request)
  request.request_header('Authorization')&.value&.split&.last
end

#extract_client_id(request) ⇒ Object



131
132
133
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 131

def extract_client_id(request)
  URI.decode_www_form(request.request_body).to_h['client_id']
end

#extract_token_from_query_params(request) ⇒ Object



140
141
142
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 140

def extract_token_from_query_params(request)
  request.query_parameters['token']
end

#find_matching_entry(ref, entries, root_url = '') ⇒ Object



196
197
198
199
200
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 196

def find_matching_entry(ref, entries, root_url = '')
  ref = "#{root_url}/#{ref}" if relative_reference?(ref) && root_url&.present?

  entries&.find { |entry| entry&.fullUrl == ref }
end

#handle_missing_required_elements(claim_entry, request) ⇒ Object



144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 144

def handle_missing_required_elements(claim_entry, request)
  request.status = 400
  request.response_headers = { 'Content-Type': 'application/json' }
  details = if claim_entry.blank?
              'Required Claim entry missing from bundle'
            else
              'Required element fullUrl missing from Claim entry'
            end
  request.response_body = FHIR::OperationOutcome.new(
    issue: FHIR::OperationOutcome::Issue.new(severity: 'fatal', code: 'required',
                                             details: FHIR::CodeableConcept.new(text: details))
  ).to_json
end

#mock_claim_response(claim, bundle, operation, root_url) ⇒ Object

Note that references from the claim to other resources in the bundle need to be changed to absolute URLs if they are relative, because the ClaimResponse’s fullUrl is a urn:uuid



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
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 63

def mock_claim_response(claim, bundle, operation, root_url)
  return FHIR::ClaimResponse.new(id: SecureRandom.uuid) if claim.blank?

  now = Time.now.utc

  FHIR::ClaimResponse.new(
    id: SecureRandom.uuid,
    meta: FHIR::Meta.new(profile: if operation == 'submit'
                                    'http://hl7.org/fhir/us/davinci-pas/StructureDefinition/profile-claimresponse'
                                  else
                                    'http://hl7.org/fhir/us/davinci-pas/StructureDefinition/profile-claiminquiryresponse'
                                  end),
    identifier: claim.identifier,
    type: claim.type,
    status: claim.status,
    use: claim.use,
    patient: absolute_reference(claim.patient, bundle.entry, root_url),
    created: now.iso8601,
    insurer: absolute_reference(claim.insurer, bundle.entry, root_url),
    requestor: absolute_reference(claim.provider, bundle.entry, root_url),
    outcome: 'complete',
    item: claim.item.map do |item|
      FHIR::ClaimResponse::Item.new(
        extension: [
          FHIR::Extension.new(
            url: 'http://hl7.org/fhir/us/davinci-pas/StructureDefinition/extension-itemPreAuthIssueDate',
            valueDate: now.strftime('%Y-%m-%d')
          ),
          FHIR::Extension.new(
            url: 'http://hl7.org/fhir/us/davinci-pas/StructureDefinition/extension-itemPreAuthPeriod',
            valuePeriod: FHIR::Period.new(start: now.strftime('%Y-%m-%d'),
                                          end: (now + 1.month).strftime('%Y-%m-%d'))
          )
        ],
        itemSequence: item.sequence,
        adjudication: [
          FHIR::ClaimResponse::Item::Adjudication.new(
            extension: [
              FHIR::Extension.new(
                url: 'http://hl7.org/fhir/us/davinci-pas/StructureDefinition/extension-reviewAction',
                extension: [
                  FHIR::Extension.new(
                    url: 'http://hl7.org/fhir/us/davinci-pas/StructureDefinition/extension-reviewActionCode',
                    valueCodeableConcept: FHIR::CodeableConcept.new(
                      coding: [
                        FHIR::Coding.new(
                          system: 'https://codesystem.x12.org/005010/306',
                          code: 'A1',
                          display: 'Certified in total'
                        )
                      ]
                    )
                  )
                ]
              )
            ],
            category: FHIR::CodeableConcept.new(
              coding: [
                FHIR::Coding.new(system: 'http://terminology.hl7.org/CodeSystem/adjudication', code: 'submitted')
              ]
            )
          )
        ]
      )
    end
  )
end

#referenced_entities(resource, entries, root_url) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 169

def referenced_entities(resource, entries, root_url)
  matches = []
  attributes = resource&.source_hash&.keys
  attributes.each do |attr|
    value = resource.send(attr.to_sym)
    if value.is_a?(FHIR::Reference) && value.reference.present?
      match = find_matching_entry(value.reference, entries, root_url)
      if match.present? && matches.none?(match)
        value.reference = match.fullUrl
        matches.concat([match], referenced_entities(match.resource, entries, root_url))
      end
    elsif value.is_a?(Array) && value.all? { |elmt| elmt.is_a?(FHIR::Model) }
      value.each { |val| matches.concat(referenced_entities(val, entries, root_url)) }
    end
  end

  matches
end

#relative_reference?(ref) ⇒ Boolean

Returns:

  • (Boolean)


203
204
205
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 203

def relative_reference?(ref)
  ref&.count('/') == 1
end

#token_response(request, _test = nil, _test_result = nil) ⇒ Object



9
10
11
12
13
# File 'lib/davinci_pas_test_kit/mock_server.rb', line 9

def token_response(request, _test = nil, _test_result = nil)
  # Placeholder for a more complete mock token endpoint
  request.response_body = { access_token: SecureRandom.hex, token_type: 'bearer', expires_in: 300 }.to_json
  request.status = 200
end