Module: DaVinciCRDTestKit::MockServiceResponse

Included in:
HookRequestEndpoint
Defined in:
lib/davinci_crd_test_kit/mock_service_response.rb

Overview

Serve responses to CRD hook invocations

Instance Method Summary collapse

Instance Method Details

#add_basic_cards(cards) ⇒ Object



225
226
227
228
229
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 225

def add_basic_cards(cards)
  cards.append(create_form_completion_card) if selected_response_types.include?('request_form_completion')
  cards.append(load_json_file('launch_smart_app.json')) if selected_response_types.include?('launch_smart_app')
  cards.append(load_json_file('external_reference.json')) if selected_response_types.include?('external_reference')
end

#add_coverage_cards(cards) ⇒ Object



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 231

def add_coverage_cards(cards)
  return unless add_coverage_cards?

  coverage = get_patient_coverage
  if coverage.present?
    if selected_response_types.include?('coverage_information') || coverage_information_required?
      system_actions =
        create_coverage_extension_system_actions(coverage.id)
    end

    if selected_response_types.include?('create_update_coverage_info')
      cards.append(create_or_update_coverage(coverage))
    end
  end
  system_actions
end

#add_coverage_cards?Boolean

Returns:

  • (Boolean)


192
193
194
195
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 192

def add_coverage_cards?
  (['coverage_information', 'create_update_coverage_info'].any? { |x| selected_response_types.include?(x) }) ||
    coverage_information_required?
end

#add_coverage_extension(resource, coverage_id) ⇒ Object



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
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 295

def add_coverage_extension(resource, coverage_id)
  resource.extension = [
    FHIR::Extension.new(
      url: 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/ext-coverage-information',
      extension: [
        FHIR::Extension.new(
          url: 'coverage',
          valueReference: FHIR::Reference.new(
            reference: "Coverage/#{coverage_id}"
          )
        ),
        FHIR::Extension.new(
          url: 'covered',
          valueCode: 'covered'
        ),
        FHIR::Extension.new(
          url: 'pa-needed',
          valueCode: 'no-auth'
        ),
        FHIR::Extension.new(
          url: 'date',
          valueDate: current_time.strftime('%Y-%m-%d')
        ),
        FHIR::Extension.new(
          url: 'coverage-assertion-id',
          valueString: SecureRandom.hex(32)
        )
      ]
    )
  ]
end

#add_order_hook_cards(cards) ⇒ Object



217
218
219
220
221
222
223
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 217

def add_order_hook_cards(cards)
  cards.append(create_companions_prerequisites_card) if selected_response_types.include?('companions_prerequisites')

  return unless selected_response_types.include?('propose_alternate_request')

  cards.append(create_alternate_request_card)
end

#contextObject



26
27
28
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 26

def context
  request_body['context']
end

#coverage_information_required?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 56

def coverage_information_required?
  coverage_information_required_hooks.include? hook_name
end

#coverage_information_required_hooksObject



8
9
10
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 8

def coverage_information_required_hooks
  ['appointment-book', 'order-dispatch', 'order-sign']
end

#create_alternate_request_cardObject



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
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 402

def create_alternate_request_card
  return if context.nil?

  propose_alternate_request_card = load_json_file('propose_alternate_request.json')

  if hook_name == 'order-dispatch'
    order_resource = get_context_resource(context['order'])
  else
    draft_orders = context['draftOrders']['entry']
    draft_order_resource = draft_orders[0]['resource']
    order_resource = FHIR.from_contents(draft_order_resource.to_json)
  end
  return if order_resource.nil?

  order_resource_type = order_resource.resourceType
  order_resource_id = order_resource.id

  card_actions = propose_alternate_request_card['suggestions'][0]['actions']
  card_actions.push(
    {
      'type' => 'delete',
      'description' => 'Remove current order until health assessment has been done',
      'resourceId' => ["#{order_resource_type}/#{order_resource_id}"]
    },
    {
      'type' => 'create',
      'description' => 'Order for patient health assessment',
      'resource' => order_resource
    }
  )
  propose_alternate_request_card
end

#create_card_response(hook_card_response) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 96

def create_card_response(hook_card_response)
  if hook_card_response.nil?
    response.headers.merge!({ 'Access-Control-Allow-Origin' => '*' })
    response.status = 400
    response.body = 'Invalid Request: Incorrect format for hook request body'
  else
    response.body = hook_card_response.to_json
    response.headers.merge!({ 'Content-Type' => 'application/json', 'Access-Control-Allow-Origin' => '*' })
    response.status = 200
    response.format = :json
  end
end

#create_cards_and_system_actionsObject



197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 197

def create_cards_and_system_actions
  return if context.nil?

  cards = []

  add_basic_cards(cards)

  add_order_hook_cards(cards)

  system_actions = add_coverage_cards(cards)

  cards.append(load_json_file('instructions.json')) if selected_response_types.include?('instructions') ||
                                                       (cards.empty? && system_actions.nil?)
  cards_response = { 'cards' => cards }
  cards_response['systemActions'] = system_actions if system_actions.present?
  cards_response
rescue StandardError
  nil
end

#create_companions_prerequisites_cardObject



393
394
395
396
397
398
399
400
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 393

def create_companions_prerequisites_card
  return if context.nil?

  companions_prerequisites_card = load_json_file('companions_prerequisites.json')
  card_service_request = companions_prerequisites_card['suggestions'][0]['actions'][0]['resource']
  update_service_request(card_service_request)
  companions_prerequisites_card
end

#create_coverage_extension_system_actions(coverage_id) ⇒ Object



248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 248

def create_coverage_extension_system_actions(coverage_id)
  update_resource = context[resource_to_update_field_name]
  prefetch_id = resource_to_update_field_name.split(/(?=[A-Z])/).first

  fhir_resource =
    if update_resource.is_a? Hash
      FHIR.from_contents(update_resource.to_json)
    elsif request_body['prefetch'] && request_body['prefetch'][prefetch_id]
      FHIR.from_contents(request_body['prefetch'][prefetch_id].to_json)
    else
      get_context_resource(update_resource)
    end

  create_system_actions(fhir_resource, coverage_id)
rescue StandardError
  nil
end

#create_coverage_resource(patient_id) ⇒ Object



327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 327

def create_coverage_resource(patient_id)
  FHIR::Coverage.new(
    id: SecureRandom.uuid,
    status: 'draft',
    beneficiary: FHIR::Reference.new(
      reference: "Patient/#{patient_id}"
    ),
    subscriber: FHIR::Reference.new(
      reference: "Patient/#{patient_id}"
    ),
    relationship: FHIR::CodeableConcept.new(
      coding: [
        FHIR::Coding.new(
          system: 'http://terminology.hl7.org/CodeSystem/subscriber-relationship',
          code: 'self'
        )
      ]
    ),
    payor: FHIR::Reference.new(
      reference: "Patient/#{patient_id}"
    )
  )
end

#create_form_completion_cardObject



372
373
374
375
376
377
378
379
380
381
382
383
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 372

def create_form_completion_card
  return if context.nil?

  request_form_completion_card = load_json_file('request_form_completion.json')
  form_completion_task = request_form_completion_card['suggestions'][0]['actions'].find do |action|
    action['resource']['resourceType'] == 'Task'
  end['resource']

  form_completion_task['for']['reference'] = "Patient/#{context['patientId']}"
  form_completion_task['authoredOn'] = current_time.strftime('%Y-%m-%d')
  request_form_completion_card
end

#create_or_update_coverage(coverage) ⇒ Object



351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 351

def create_or_update_coverage(coverage)
  return if context.nil?

  if coverage.present?
    action = { 'type' => 'update', 'description' => 'Update current coverage record' }
    coverage.period =
      FHIR::Period.new(
        start: current_time.strftime('%Y-%m-%d'),
        end: (current_time + 1.month).strftime('%Y-%m-%d')
      )
    action['resource'] = coverage
  else
    action = { 'type' => 'create', 'description' => 'Create coverage record' }
    new_coverage = create_coverage_resource(context['patientId'])
    action['resource'] = new_coverage
  end
  coverage_info_card = load_json_file('create_update_coverage_information.json')
  coverage_info_card['suggestions'][0]['actions'] = [action]
  coverage_info_card
end

#create_system_actions(resource, coverage_id) ⇒ Object



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
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 266

def create_system_actions(resource, coverage_id)
  return if resource.nil?

  system_actions = []
  if resource.resourceType == 'Bundle'
    resource.entry.each do |entry|
      entry_resource = entry.resource
      add_coverage_extension(entry_resource, coverage_id)
      system_actions.append(
        {
          'type' => 'update',
          'description' => "Added coverage information to #{entry_resource.resourceType} resource.",
          'resource' => entry_resource
        }
      )
    end
  else
    add_coverage_extension(resource, coverage_id)
    system_actions.append(
      {
        'type' => 'update',
        'description' => "Added coverage information to #{resource.resourceType} resource.",
        'resource' => resource
      }
    )
  end
  system_actions
end

#create_warning_messages(hook_card_response) ⇒ Object



74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 74

def create_warning_messages(hook_card_response)
  return if custom_response.present?

  missing_response_types =
    if hook_card_response.nil?
      selected_response_types
    else
      get_missing_response_types(hook_card_response)
    end

  return if missing_response_types.empty?

  missing_response_types = format_missing_response_types(missing_response_types)
  missing_response_types.each do |missing_response_type|
    Inferno::Repositories::Messages.new.create(
      result_id: result.id,
      type: 'warning',
      message: %(Unable to return response type: `#{missing_response_type}` for #{hook_name} hook)
    )
  end
end

#current_timeObject



4
5
6
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 4

def current_time
  Time.now.utc
end

#format_missing_response_types(missing_response_types) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 30

def format_missing_response_types(missing_response_types)
  missing_response_types
    .map do |response_type|
    response_type_string =
      response_type.split('_')
        .map(&:capitalize)
        .join(' ')
        .sub('Smart', 'SMART')
        .sub('Create Update', 'Create/Update')
        .sub('Companions Prerequisites', 'Companions/Prerequisites')
    response_type_string
  end
end

#get_context_resource(update_resource_id) ⇒ Object



180
181
182
183
184
185
186
187
188
189
190
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 180

def get_context_resource(update_resource_id)
  update_resource_id = "#{resource_type_to_update}/#{update_resource_id}" unless update_resource_id.include? '/'
  fhir_server = request_body['fhirServer']
  return if fhir_server.blank?

  access_token = request_body['fhirAuthorization']['access_token'] if request_body['fhirAuthorization']
  make_resource_request(
    "#{fhir_server}/#{update_resource_id}",
    access_token
  )
end

#get_missing_response_types(hook_card_response) ⇒ Object



60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 60

def get_missing_response_types(hook_card_response)
  selected_response_types.append('coverage_information').uniq! if coverage_information_required?

  selected_response_types
    .select do |response_type|
      response_type = response_type
        .split('_')
        .join(' ')
        .sub('create update', 'create/update')
        .sub('companions prerequisites', 'companions/prerequisites')
      missing_response_type_filter(response_type, hook_card_response)
    end
end

#get_patient_coverageObject

rubocop:disable Naming/AccessorMethodName



162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 162

def get_patient_coverage # rubocop:disable Naming/AccessorMethodName
  prefetch = request_body['prefetch']
  if prefetch.present? && prefetch['coverage']
    FHIR.from_contents(prefetch['coverage'].to_json)
  else
    fhir_server = request_body['fhirServer']
    if fhir_server.present?
      access_token = request_body['fhirAuthorization']['access_token'] if request_body['fhirAuthorization']
      patient_id = context['patientId']

      make_resource_request(
        "#{fhir_server}/Coverage?patient=#{patient_id}&status=active",
        access_token
      )
    end
  end
end

#hook_responseObject



138
139
140
141
142
143
144
145
146
147
148
149
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 138

def hook_response
  hook_card_response =
    if custom_response.present?
      JSON.parse(custom_response)
    else
      cards_response = create_cards_and_system_actions
      update_specific_hook_card_info(cards_response)
    end

  create_warning_messages(hook_card_response)
  create_card_response(hook_card_response)
end

#load_json_file(filename) ⇒ Object



12
13
14
15
16
17
18
19
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 12

def load_json_file(filename)
  json = JSON.parse(File.read(File.join(__dir__, 'card_responses', filename)))
  return json unless filename == 'launch_smart_app.json'

  json['links'].first['url'] = "#{Inferno::Application['base_url']}/custom/smart/launch"

  json
end

#make_resource_request(uri, access_token) ⇒ Object



151
152
153
154
155
156
157
158
159
160
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 151

def make_resource_request(uri, access_token)
  response = Faraday.get(uri, nil, { 'Authorization' => "Bearer #{access_token}" })
  return unless response.status == 200

  resource = FHIR.from_contents(response.body)
  return resource unless resource.resourceType == 'Bundle'
  return if resource.entry.empty?

  resource.entry.first.resource
end

#missing_response_type_filter(response_type, hook_card_response) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 44

def missing_response_type_filter(response_type, hook_card_response)
  if response_type == 'coverage information'
    hook_card_response['systemActions'].nil? ||
      hook_card_response['systemActions'].none? do |card|
        card['description'].include?('coverage information')
      end
  else
    hook_card_response['cards'].present? &&
      hook_card_response['cards'].none? { |card| card['summary'].downcase.include?(response_type) }
  end
end

#request_bodyObject



21
22
23
24
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 21

def request_body
  @request_body ||=
    JSON.parse(request.params.to_json)
end

#resource_to_update_field_nameObject



120
121
122
123
124
125
126
127
128
129
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 120

def resource_to_update_field_name
  {
    'appointment-book' => 'appointments',
    'encounter-start' => 'encounterId',
    'encounter-discharge' => 'encounterId',
    'order-dispatch' => 'order',
    'order-select' => 'draftOrders',
    'order-sign' => 'draftOrders'
  }[hook_name]
end

#resource_type_to_updateObject



131
132
133
134
135
136
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 131

def resource_type_to_update
  {
    'encounter-start' => 'Encounter',
    'encounter-discharge' => 'Encounter'
  }[hook_name]
end

#update_service_request(service_request) ⇒ Object



385
386
387
388
389
390
391
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 385

def update_service_request(service_request)
  return if context.nil?

  service_request['subject']['reference'] = "Patient/#{context['patientId']}"
  service_request['requester']['reference'] = context['userId']
  service_request['authoredOn'] = current_time.strftime('%Y-%m-%d')
end

#update_specific_hook_card_info(card_response) ⇒ Object



109
110
111
112
113
114
115
116
117
118
# File 'lib/davinci_crd_test_kit/mock_service_response.rb', line 109

def update_specific_hook_card_info(card_response)
  return if card_response.nil?

  hook_display = hook_name.split('-').map(&:capitalize).join(' ')
  card_response['cards'].map do |card|
    card['summary'].prepend("#{hook_display} ")
    card['uuid'] = SecureRandom.uuid
  end
  card_response
end