Module: DaVinciCRDTestKit::HookRequestFieldValidation

Included in:
ClientHookRequestValidation, ServerHookRequestValidation
Defined in:
lib/davinci_crd_test_kit/hook_request_field_validation.rb

Instance Method Summary collapse

Instance Method Details

#appointment_book_context_check(context) ⇒ Object



342
343
344
345
346
347
348
349
350
351
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 342

def appointment_book_context_check(context)
  hook_user_type_check(context, 'appointment-book')
  id_only_fields_check('appointment-book', context, ['patientId'])

  appointment_bundle = parse_fhir_bundle_from_context('appointments', context)
  return if appointment_bundle.blank?

  expected_resource_types = ['Appointment']
  bundle_entries_check(context, 'appointments', appointment_bundle, expected_resource_types, 'proposed')
end

#bundle_entries_check(context, context_field_name, bundle, resource_types, status = nil) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 288

def bundle_entries_check(context, context_field_name, bundle, resource_types, status = nil)
  target_resources = bundle.entry.map(&:resource).select { |r| resource_types.include?(r.resourceType) }
  if target_resources.blank?
    error_msg = "#{request_number}`#{context_field_name}` bundle must contain at least one of the " \
                "expected resource types: #{resource_types.to_sentence}. In Context `#{context}`"
    add_message('error', error_msg)
    return
  end

  status_check(context, context_field_name, status, target_resources)

  target_resources.each do |resource|
    resource_is_valid?(resource:, profile_url: structure_definition_map[resource.resourceType])
  end
end

#check_patient_scope_requirement(scopes, fhir_authorization) ⇒ Object



148
149
150
151
152
153
154
155
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 148

def check_patient_scope_requirement(scopes, fhir_authorization)
  if scopes.any? { |scope| scope.start_with?('patient/') } &&
     !(fhir_authorization['patient'] && fhir_authorization['patient'].is_a?(String))
    info %(
       #{request_number}The `patient` field for request SHOULD be populated to identify the FHIR id of that
       patient when the granted SMART scopes include patient scopes)
  end
end

#common_context_fieldsObject



44
45
46
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 44

def common_context_fields
  { 'userId' => String, 'patientId' => String }.freeze
end

#context_optional_fields_by_hookObject



59
60
61
62
63
64
65
66
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 59

def context_optional_fields_by_hook
  {
    'appointment-book' => { 'encounterId' => String },
    'order-select' => { 'encounterId' => String },
    'order-dispatch' => { 'task' => Hash },
    'order-sign' => { 'encounterId' => String }
  }.freeze
end

#context_required_fields_by_hookObject



48
49
50
51
52
53
54
55
56
57
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 48

def context_required_fields_by_hook
  {
    'appointment-book' => common_context_fields.merge('appointments' => Hash),
    'encounter-start' => common_context_fields.merge('encounterId' => String),
    'encounter-discharge' => common_context_fields.merge('encounterId' => String),
    'order-select' => common_context_fields.merge('selections' => Array, 'draftOrders' => Hash),
    'order-dispatch' => { 'patientId' => String, 'order' => String, 'performer' => String },
    'order-sign' => common_context_fields.merge('draftOrders' => Hash)
  }.freeze
end

#context_selections_check(context, selections, order_refs, expected_resource_types) ⇒ Object



329
330
331
332
333
334
335
336
337
338
339
340
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 329

def context_selections_check(context, selections, order_refs, expected_resource_types)
  return unless selections.is_a?(Array)

  selections.each do |reference|
    resource_reference_check(reference, 'selections item', supported_resource_types: expected_resource_types)
    next if order_refs.include?(reference)

    error_msg = "#{request_number}`selections` field must reference FHIR resources in `draftOrders`. " \
                "#{reference} is not in `draftOrders`. In Context `#{context}`"
    add_message('error', error_msg)
  end
end

#context_user_types_by_hookObject



74
75
76
77
78
79
80
81
82
83
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 74

def context_user_types_by_hook
  shared_resources = ['Practitioner', 'PractitionerRole']
  {
    'appointment-book' => ['Patient', 'RelatedPerson'].concat(shared_resources),
    'encounter-start' => shared_resources,
    'encounter-discharge' => shared_resources,
    'order-select' => shared_resources,
    'order-sign' => shared_resources
  }.freeze
end

#context_validate_optional_fields(hook_context, hook_name) ⇒ Object



426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 426

def context_validate_optional_fields(hook_context, hook_name)
  hook_optional_context_fields = context_optional_fields_by_hook[hook_name]
  return if hook_optional_context_fields.blank?

  hook_optional_context_fields.each do |field, type|
    validate_presence_and_type(hook_context, field, type, "#{hook_name} request context") if hook_context[field]
  end

  optional_field_keys = hook_optional_context_fields.keys
  if optional_field_keys.include?('encounterId') && hook_context['encounterId'].present?
    id_only_fields_check(hook_name, hook_context, ['encounterId'])
  end

  validate_hash_fields(hook_context, optional_field_keys)
end

#encounter_start_or_discharge_context_check(context, hook_name) ⇒ Object



353
354
355
356
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 353

def encounter_start_or_discharge_context_check(context, hook_name)
  hook_user_type_check(context, hook_name)
  id_only_fields_check(hook_name, context, ['patientId', 'encounterId'])
end

#fhir_auth_fields_valid?(fhir_authorization_required_fields, fhir_authorization) ⇒ Boolean

Returns:

  • (Boolean)


133
134
135
136
137
138
139
140
141
142
143
144
145
146
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 133

def fhir_auth_fields_valid?(fhir_authorization_required_fields, fhir_authorization)
  fhir_auth_valid = true
  fhir_authorization_required_fields.each do |field, type|
    if fhir_authorization[field].blank?
      add_message('error', "#{request_number}`fhirAuthorization` did not contain required field: `#{field}`")
      fhir_auth_valid = false
    end
    unless fhir_authorization[field].is_a?(type)
      add_message('error', "#{request_number}`fhirAuthorization` field #{field} is not of type #{type}")
      fhir_auth_valid = false
    end
  end
  fhir_auth_valid
end

#fhir_authorization_required_fieldsObject



26
27
28
29
30
31
32
33
34
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 26

def fhir_authorization_required_fields
  {
    'access_token' => String,
    'token_type' => String,
    'expires_in' => Integer,
    'scope' => String,
    'subject' => String
  }
end

#hook_optional_fieldsObject



36
37
38
39
40
41
42
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 36

def hook_optional_fields
  {
    'fhirServer' => String,
    'fhirAuthorization' => Hash,
    'prefetch' => Hash
  }
end

#hook_request_context_check(context, hook_name) ⇒ Object



209
210
211
212
213
214
215
216
217
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 209

def hook_request_context_check(context, hook_name)
  required_fields = context_required_fields_by_hook[hook_name]
  required_fields.each do |field, type|
    validate_presence_and_type(context, field, type,
                               "#{request_number}#{hook_name} request context")
  end
  context_validate_optional_fields(context, hook_name)
  hook_specific_context_check(context, hook_name)
end

#hook_request_fhir_auth_check(request_body) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 157

def hook_request_fhir_auth_check(request_body)
  if request_body['fhirAuthorization']

    fhir_authorization = request_body['fhirAuthorization']

    return unless fhir_auth_fields_valid?(fhir_authorization_required_fields, fhir_authorization)

    if fhir_authorization['token_type'] != 'Bearer'
      add_message('error', "#{request_number}`fhirAuthorization` `token_type` field is not set to 'Bearer'")
    end

    access_token = fhir_authorization['access_token']

    scopes = fhir_authorization['scope'].split

    check_patient_scope_requirement(scopes, fhir_authorization)
  end
  { fhir_server_uri: request_body['fhirServer'], fhir_access_token: access_token }
end

#hook_request_optional_fields_check(request_body) ⇒ Object



177
178
179
180
181
182
183
184
185
186
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 177

def hook_request_optional_fields_check(request_body)
  hook_optional_fields.each do |field, type|
    info "#{request_number}Hook request did not contain optional field: `#{field}`" if request_body[field].blank?

    if request_body[field] && !request_body[field].is_a?(type)
      add_message('error', "#{request_number}Hook request field #{field} is not of type #{type}")
    end
  end
  hook_request_fhir_auth_check(request_body)
end

#hook_request_prefetch_check(advertised_prefetch_fields, received_prefetch, received_context) ⇒ Object



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

def hook_request_prefetch_check(advertised_prefetch_fields, received_prefetch, received_context)
  advertised_prefetch_fields.each do |advertised_prefetch_key, advertised_prefetch_template|
    next if received_prefetch[advertised_prefetch_key].blank?

    unless received_prefetch[advertised_prefetch_key].is_a?(Hash)
      add_message('error', "#{request_number}Prefetch field `#{advertised_prefetch_key}` is not of type `Hash`.")
      next
    end

    received_prefetch_resource = FHIR.from_contents(received_prefetch[advertised_prefetch_key].to_json)

    if advertised_prefetch_template.include?('?')
      advertised_prefetch_fhir_search = advertised_prefetch_template.gsub(/{|}/, '').split('?')
      advertised_prefetch_resource_type = advertised_prefetch_fhir_search.first

      if advertised_prefetch_resource_type == 'Coverage'
        advertised_coverage_query_params = Rack::Utils.parse_nested_query(advertised_prefetch_fhir_search.last)

        advertised_patient_token = advertised_coverage_query_params['patient']
        advertised_context_patient_id_key = advertised_patient_token.split('.').last
        received_context_patient_id = received_context[advertised_context_patient_id_key]

        advertised_status_param = advertised_coverage_query_params['status']

        validate_prefetch_coverage(received_prefetch_resource, advertised_prefetch_key, received_context_patient_id,
                                   advertised_status_param)
      end
    else
      advertised_prefetch_token = advertised_prefetch_template.gsub(/{|}/, '').split('/')
      advertised_context_id = advertised_prefetch_token.last.split('.').last

      if advertised_prefetch_token.length == 1
        received_context_reference = FHIR::Reference.new(reference: received_context[advertised_context_id])
        received_context_resource_type = received_context_reference.resource_type
        received_context_id = received_context_reference.reference_id
      else
        received_context_id = received_context[advertised_context_id]
        received_context_resource_type = advertised_prefetch_token.first
      end
      validate_prefetch_resource(received_prefetch_resource, advertised_prefetch_key,
                                 received_context_resource_type, received_context_id)
    end
  end
end

#hook_request_required_fields_check(request_body, hook_name) ⇒ Object



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

def hook_request_required_fields_check(request_body, hook_name)
  hook_required_fields.each do |field, type|
    if request_body[field].blank?
      add_message('error', "#{request_number}Hook request did not contain required field: `#{field}`")
      next
    end

    unless request_body[field].is_a?(type)
      add_message('error', "#{request_number}Hook request field #{field} is not of type #{type}")
      next
    end
  end

  if request_body['hook'] != hook_name
    add_message('error',
                "#{request_number}The `hook` field should be #{hook_name}, but was #{request_body['hook']}")
    return
  end

  return unless request_body['fhirAuthorization'].present? && request_body['fhirServer'].blank?

  add_message('error', %(
              #{request_number}Missing `fhirServer` field: If `fhirAuthorization` is provided, this field is
              #REQUIRED.))
end

#hook_required_fieldsObject



18
19
20
21
22
23
24
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 18

def hook_required_fields
  {
    'hook' => String,
    'hookInstance' => String,
    'context' => Hash
  }
end

#hook_specific_context_check(context, hook_name) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 219

def hook_specific_context_check(context, hook_name)
  case hook_name
  when 'appointment-book'
    appointment_book_context_check(context)
  when 'encounter-start', 'encounter-discharge'
    encounter_start_or_discharge_context_check(context, hook_name)
  when 'order-select', 'order-sign'
    order_select_or_sign_context_check(context, hook_name)
  when 'order-dispatch'
    order_dispatch_context_check(context)
  end
end

#hook_user_type_check(context, hook_name) ⇒ Object



232
233
234
235
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 232

def hook_user_type_check(context, hook_name)
  supported_resource_types = context_user_types_by_hook[hook_name]
  resource_reference_check(context['userId'], 'userId', supported_resource_types:)
end

#id_only_fields_check(hook_name, context, id_fields) ⇒ Object



265
266
267
268
269
270
271
272
273
274
275
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 265

def id_only_fields_check(hook_name, context, id_fields)
  id_fields.each do |field|
    resource_id = context[field]
    next unless resource_id.is_a?(String) && valid_id_format?(field, hook_name, resource_id)

    if client_test?
      resource_type = field.split(/(?=[A-Z])/).first.capitalize
      query_and_validate_id_field(resource_type, resource_id)
    end
  end
end

#json_parse(json) ⇒ Object



11
12
13
14
15
16
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 11

def json_parse(json)
  JSON.parse(json)
rescue JSON::ParserError
  add_message('error', "#{request_number}Invalid JSON.")
  false
end

#no_error_validation(message) ⇒ Object



390
391
392
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 390

def no_error_validation(message)
  assert messages.none? { |msg| msg[:type] == 'error' }, message
end

#optional_field_resource_typesObject



68
69
70
71
72
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 68

def optional_field_resource_types
  {
    'task' => 'Task'
  }
end

#order_dispatch_context_check(context) ⇒ Object



380
381
382
383
384
385
386
387
388
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 380

def order_dispatch_context_check(context)
  id_only_fields_check('order-dispatch', context, ['patientId'])
  order_supported_resource_type = [
    'DeviceRequest', 'MedicationRequest', 'NutritionOrder',
    'ServiceRequest', 'VisionPrescription'
  ]
  resource_reference_check(context['order'], 'order', supported_resource_types: order_supported_resource_type)
  resource_reference_check(context['performer'], 'performer')
end

#order_select_or_sign_context_check(context, hook_name) ⇒ Object



358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 358

def order_select_or_sign_context_check(context, hook_name)
  hook_user_type_check(context, hook_name)
  id_only_fields_check(hook_name, context, ['patientId'])

  draft_orders_bundle = parse_fhir_bundle_from_context('draftOrders', context)
  return if draft_orders_bundle.blank?

  expected_resource_types = [
    'DeviceRequest', 'MedicationRequest', 'NutritionOrder',
    'ServiceRequest', 'VisionPrescription'
  ]

  bundle_entries_check(context, 'draftOrders', draft_orders_bundle, expected_resource_types)

  return unless hook_name == 'order-select'

  order_refs = draft_orders_bundle.entry.map(&:resource).map do |resource|
    "#{resource.resourceType}/#{resource.id}"
  end
  context_selections_check(context, context['selections'], order_refs, expected_resource_types)
end

#parse_fhir_bundle_from_context(context_field_name, context) ⇒ Object



312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 312

def parse_fhir_bundle_from_context(context_field_name, context)
  fhir_bundle = FHIR.from_contents(context[context_field_name].to_json)
  if fhir_bundle.blank?
    error_msg = "#{request_number}`#{context_field_name}` field is not a FHIR resource: " \
                "`#{context[context_field_name]}`. In Context `#{context}`"
    add_message('error', error_msg)
    return
  end

  return fhir_bundle if fhir_bundle.is_a?(FHIR::Bundle)

  error_msg = "#{request_number}Wrong context resource type: Expected `Bundle`, got " \
              "`#{fhir_bundle.resourceType}`. In Context `#{context}`"
  add_message('error', error_msg)
  nil
end

#query_and_validate_id_field(resource_type, resource_id) ⇒ Object



401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 401

def query_and_validate_id_field(resource_type, resource_id)
  fhir_read(resource_type, resource_id)
  status = request.response[:status]
  unless status == 200
    add_message('error', "#{request_number}Unexpected response status: expected 200, but received #{status}")
    return
  end
  unless resource.resourceType == resource_type
    add_message('error', %(
      #{request_number}Unexpected resource type: Expected `#{resource_type}`. Got
      `#{resource.resourceType}`.
    ))
    return
  end
  unless resource.id == resource_id
    add_message('error', %(
      #{request_number}Requested resource with id #{resource_id}, received resource with id #{resource.id}
      ))
    return
  end

  profile_url = hook_name == 'order-dispatch' ? nil : structure_definition_map[resource_type]
  resource_is_valid?(profile_url:)
end

#request_numberObject



3
4
5
6
7
8
9
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 3

def request_number
  if @request_number.blank?
    ''
  else
    "Request #{@request_number}: "
  end
end

#resource_reference_check(reference, field_name, supported_resource_types: nil) ⇒ Object



237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 237

def resource_reference_check(reference, field_name, supported_resource_types: nil)
  return unless reference.is_a?(String) && valid_reference_format?(reference, field_name)

  resource_type, resource_id = reference.split('/')

  if supported_resource_types && !supported_resource_types.include?(resource_type)
    error_msg = "#{request_number}Unsupported resource type: `#{field_name}` type should be one " \
                "of the following: #{supported_resource_types.to_sentence}, but " \
                "received #{resource_type}."

    add_message('error', error_msg)
    return
  end

  query_and_validate_id_field(resource_type, resource_id) if client_test? && !field_name.include?('selections')
end

#status_check(context, context_field_name, status, resources) ⇒ Object



304
305
306
307
308
309
310
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 304

def status_check(context, context_field_name, status, resources)
  return unless status && !resources.all? { |resource| resource.status == status }

  error_msg = "#{request_number}All #{resources.map(&:resourceType).uniq.to_sentence} resources in " \
              "`#{context_field_name}` bundle must have a `#{status}` status. In Context `#{context}`"
  add_message('error', error_msg)
end

#structure_definition_mapObject



85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 85

def structure_definition_map
  {
    'Practitioner' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-practitioner',
    'PractitionerRole' => 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-practitionerrole',
    'Patient' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-patient',
    'Encounter' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-encounter',
    'Appointment' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-appointment',
    'DeviceRequest' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-devicerequest',
    'MedicationRequest' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-medicationrequest',
    'NutritionOrder' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-nutritionorder',
    'ServiceRequest' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-servicerequest',
    'VisionPrescription' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-visionprescription',
    'Medication' => 'http://hl7.org/fhir/us/core/StructureDefinition/us-core-medication',
    'Device' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-device',
    'CommunicationRequest' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-communicationrequest',
    'Task' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-taskquestionnaire',
    'Coverage' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-coverage',
    'Location' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-location',
    'Organization' => 'http://hl7.org/fhir/us/davinci-crd/StructureDefinition/profile-organization'
  }.freeze
end

#valid_id_format?(field, hook_name, resource_id) ⇒ Boolean

Returns:

  • (Boolean)


277
278
279
280
281
282
283
284
285
286
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 277

def valid_id_format?(field, hook_name, resource_id)
  if resource_id.include?('/')
    error_msg = %(
      #{request_number}`#{field}` in #{hook_name} context should be a plain ID, not a reference.
      Got: `#{resource_id}`.)
    add_message('error', error_msg)
    false
  end
  true
end

#valid_reference_format?(reference, field_name) ⇒ Boolean

Returns:

  • (Boolean)


254
255
256
257
258
259
260
261
262
263
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 254

def valid_reference_format?(reference, field_name)
  resource_type, resource_id = reference.split('/')
  return true if resource_type.present? && resource_id.present?

  add_message('error', %(
    #{request_number}Invalid `#{field_name}` format. Expected `{resourceType}/{id}`,
    received `#{reference}`.
  ))
  false
end

#valid_url?(url) ⇒ Boolean

Returns:

  • (Boolean)


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

def valid_url?(url)
  uri = URI.parse(url)
  uri.host.present? && ['http', 'https'].include?(uri.scheme)
rescue URI::InvalidURIError
  false
end

#validate_hash_fields(hook_context, hook_optional_context_fields) ⇒ Object



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

def validate_hash_fields(hook_context, hook_optional_context_fields)
  hash_context_fields = hook_context.select do |field, value|
    value.is_a?(Hash) && hook_optional_context_fields.include?(field)
  end

  return if hash_context_fields.empty?

  hash_context_fields.each do |field, entry|
    resource_json = entry.to_json
    fhir_resource = FHIR.from_contents(resource_json)
    if fhir_resource.blank?
      add_message('error', "#{request_number}Field `#{field}` is not a FHIR resource.")
      next
    end
    resource_type = optional_field_resource_types[field]
    unless fhir_resource.resourceType == resource_type
      add_message('error', %(
        #{request_number}Field `#{field}` must be a `#{resource_type}`. Got
        `#{fhir_resource.resourceType}`.
      ))
      next
    end
    resource_is_valid?(resource: fhir_resource)
  end
end

#validate_prefetch_coverage(received_resource, advertised_prefetch_key, received_context_patient_id, advertised_status) ⇒ Object



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

def validate_prefetch_coverage(received_resource, advertised_prefetch_key,
                               received_context_patient_id, advertised_status)
  unless received_resource.resourceType == 'Bundle'
    add_message('error', %(
      #{request_number}Unexpected resource type: Expected `Bundle`. Got
      `#{received_resource.resourceType}`.
    ))
    return
  end

  if received_resource.entry.empty?
    add_message('error', "#{request_number}Bundle of coverage resources received from prefetch is empty")
    return
  end

  coverage_resource = received_resource.entry.first.resource
  unless coverage_resource.resourceType == 'Coverage'
    add_message('error', %(
      #{request_number}Unexpected resource type: Expected `Coverage`. Got
      `#{coverage_resource.resourceType}`.
    ))
    return
  end

  resource_is_valid?(resource: coverage_resource,
                     profile_url: structure_definition_map['Coverage'])

  coverage_beneficiary_reference = coverage_resource.beneficiary
  coverage_beneficiary_patient_id = coverage_beneficiary_reference.reference_id
  if coverage_beneficiary_patient_id.blank?
    add_message('error', %(
      #{request_number}Could not get beneficiary reference id from `#{advertised_prefetch_key}` field's Coverage
      resource
    ))
    return
  end

  if coverage_beneficiary_patient_id != received_context_patient_id
    add_message('error', %(
      #{request_number}Expected `#{advertised_prefetch_key}` field's Coverage resource to have a `beneficiary`
      reference id of '#{received_context_patient_id}', instead was '#{coverage_beneficiary_patient_id}'
    ))
    return
  end

  coverage_status = coverage_resource.status
  return unless coverage_status != advertised_status

  add_message('error', %(
      #{request_number}Expected `#{advertised_prefetch_key}` field's Coverage resource to have a `status` of
      '#{advertised_status}', instead was '#{coverage_status}'
    ))
end

#validate_prefetch_resource(received_resource, advertised_prefetch_key, context_field_resource_type, context_field_id) ⇒ Object



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

def validate_prefetch_resource(received_resource, advertised_prefetch_key, context_field_resource_type,
                               context_field_id)
  unless received_resource.resourceType == context_field_resource_type
    add_message('error', %(
      #{request_number}Unexpected resource type: Expected `#{context_field_resource_type}`. Got
      `#{received_resource.resourceType}`.
    ))
    return
  end

  if hook_name == 'order-dispatch'
    resource_is_valid?(resource: received_resource)
  else
    resource_is_valid?(resource: received_resource,
                       profile_url: structure_definition_map[context_field_resource_type])
  end

  received_prefetch_resource_id = received_resource.id
  if received_prefetch_resource_id.blank?
    add_message('error', %(
      #{request_number}#{advertised_prefetch_key}` field's FHIR resource does not contain the `id` field
    ))
    return
  end

  return unless received_prefetch_resource_id != context_field_id

  add_message('error', %(
    #{request_number}Expected `#{advertised_prefetch_key}` field's FHIR resource to have an `id` of
    '#{context_field_id}', instead was '#{received_prefetch_resource_id}'
  ))
end

#validate_presence_and_type(object, field_name, type, description = '') ⇒ Object



188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/davinci_crd_test_kit/hook_request_field_validation.rb', line 188

def validate_presence_and_type(object, field_name, type, description = '')
  value = object[field_name]
  unless value
    error_msg = "#{description} does not contain required field `#{field_name}`: #{description} `#{object}`."
    add_message('error', error_msg)
    return
  end

  is_valid_type = type == 'URL' ? valid_url?(value) : value.is_a?(type)
  unless is_valid_type
    error_msg = type == 'URL' ? 'is not a valid URL' : "is not of type `#{type}`"
    add_message('error', "#{description} field `#{field_name}` #{error_msg}: #{description} `#{object}`.")
    return
  end

  return unless value.blank?

  error_msg = "#{description} field `#{field_name}` should not be an empty #{type}: #{description} `#{object}`."
  add_message('error', error_msg)
end