index
int64 0
0
| repo_id
stringclasses 829
values | file_path
stringlengths 34
254
| content
stringlengths 6
5.38M
|
|---|---|---|---|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/appeal_submission.rb
|
# frozen_string_literal: true
require 'decision_review/utilities/saved_claim/service'
class AppealSubmission < ApplicationRecord
include DecisionReview::SavedClaim::Service
APPEAL_TYPES = %w[HLR NOD SC].freeze
validates :submitted_appeal_uuid, presence: true
belongs_to :user_account, dependent: nil, optional: false
validates :type_of_appeal, inclusion: APPEAL_TYPES
has_kms_key
has_encrypted :upload_metadata, key: :kms_key, **lockbox_options
has_many :appeal_submission_uploads, dependent: :destroy
has_many :secondary_appeal_forms, dependent: :destroy
has_many :incomplete_secondary_appeal_forms, lambda {
where(delete_date: nil)
}, class_name: 'SecondaryAppealForm', dependent: nil, inverse_of: :appeal_submission
# Work around for a polymorphic association, each AppealSubmission will only have one of the following: sc, hlr, nod
has_one :saved_claim_sc, class_name: 'SavedClaim::SupplementalClaim', foreign_key: :guid,
primary_key: :submitted_appeal_uuid,
dependent: :restrict_with_exception,
inverse_of: :appeal_submission,
required: false
has_one :saved_claim_hlr, class_name: 'SavedClaim::HigherLevelReview', foreign_key: :guid,
primary_key: :submitted_appeal_uuid,
dependent: :restrict_with_exception,
inverse_of: :appeal_submission,
required: false
has_one :saved_claim_nod, class_name: 'SavedClaim::NoticeOfDisagreement', foreign_key: :guid,
primary_key: :submitted_appeal_uuid,
dependent: :restrict_with_exception,
inverse_of: :appeal_submission,
required: false
scope :failure_not_sent, -> { where(failure_notification_sent_at: nil).order(id: :asc) }
def self.submit_nod(request_body_hash:, current_user:, decision_review_service: nil)
ActiveRecord::Base.transaction do
raise 'Must pass in a version of the DecisionReview Service' if decision_review_service.nil?
appeal_submission = new(type_of_appeal: 'NOD',
user_account: current_user.user_account,
board_review_option: request_body_hash['data']['attributes']['boardReviewOption'],
upload_metadata: decision_review_service.class.file_upload_metadata(current_user))
form = request_body_hash.to_json # serialize before modifications are made to request body
uploads_arr = request_body_hash.delete('nodUploads') || []
nod_response_body = decision_review_service.create_notice_of_disagreement(request_body: request_body_hash,
user: current_user)
.body
guid = nod_response_body.dig('data', 'id')
appeal_submission.submitted_appeal_uuid = guid
appeal_submission.save!
appeal_submission.store_saved_claim(claim_class: SavedClaim::NoticeOfDisagreement, form:, guid:)
# Clear in-progress form if submit was successful
InProgressForm.form_for_user('10182', current_user)&.destroy!
appeal_submission.enqueue_uploads(uploads_arr, current_user)
nod_response_body
end
end
def enqueue_uploads(uploads_arr, _user)
uploads_arr.each do |upload_attrs|
asu = AppealSubmissionUpload.create!(decision_review_evidence_attachment_guid: upload_attrs['confirmationCode'],
appeal_submission_id: id)
DecisionReviews::SubmitUpload.perform_async(asu.id)
end
end
def current_email_address
sc = SavedClaim.find_by(guid: submitted_appeal_uuid)
form = JSON.parse(sc.form)
email = form.dig('data', 'attributes', 'veteran', 'email')
raise 'Failed to retrieve email address' if email.nil?
email
end
def get_mpi_profile
@mpi_profile ||= begin
response = MPI::Service.new.find_profile_by_identifier(identifier: user_account.icn,
identifier_type: MPI::Constants::ICN)&.profile
raise 'Failed to fetch MPI profile' if response.nil?
response
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user_credential_email.rb
|
# frozen_string_literal: true
class UserCredentialEmail < ApplicationRecord
belongs_to :user_verification, dependent: nil, optional: false
has_kms_key
has_encrypted :credential_email, key: :kms_key, **lockbox_options
validates :credential_email_ciphertext, presence: true
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user_session_form.rb
|
# frozen_string_literal: true
class UserSessionForm
include ActiveModel::Validations
VALIDATIONS_FAILED_ERROR_CODE = '004'
SAML_REPLAY_VALID_SESSION_ERROR_CODE = '002'
ERRORS = { validations_failed: { code: VALIDATIONS_FAILED_ERROR_CODE,
tag: :validations_failed,
short_message: 'on User/Session Validation',
level: :error },
saml_replay_valid_session: { code: SAML_REPLAY_VALID_SESSION_ERROR_CODE,
tag: :saml_replay_valid_session,
short_message: 'SamlResponse is too late but user has current session',
level: :warn } }.freeze
attr_reader :user, :user_identity, :session, :saml_uuid
def initialize(saml_response)
@saml_uuid = saml_response.in_response_to
saml_user = SAML::User.new(saml_response)
saml_attributes = normalize_saml(saml_user)
user_verification = create_user_verification(saml_attributes)
uuid = user_verification.user_account.id
existing_user = User.find(uuid)
@session = Session.new(uuid:, ssoe_transactionid: saml_user.user_attributes.try(:transactionid))
@user_identity = UserIdentity.new(saml_attributes.merge(uuid:))
@user = User.new(uuid:)
@user.session_handle = @session.token
@user.instance_variable_set(:@identity, @user_identity)
@user.invalidate_mpi_cache
if saml_user.changing_multifactor?
last_signed_in = existing_user&.last_signed_in || Time.current.utc
@user.mhv_last_signed_in = last_signed_in
@user.last_signed_in = last_signed_in
log_existing_user_warning(uuid, saml_attributes[:mhv_icn]) unless existing_user
else
@user.last_signed_in = Time.current.utc
end
end
def normalize_saml(saml_user)
saml_user.validate!
saml_user_attributes = saml_user.to_hash
add_csp_id_to_mpi(saml_user_attributes, saml_user_attributes[:idme_uuid]) if saml_user.needs_csp_id_mpi_update?
saml_user_attributes
rescue SAML::UserAttributeError => e
raise unless e.code == SAML::UserAttributeError::UUID_MISSING_CODE
idme_uuid = uuid_from_account(e&.identifier)
raise if idme_uuid.blank?
Rails.logger.info('Account UUID injected into user SAML attributes')
saml_user_attributes = saml_user.to_hash
add_csp_id_to_mpi(saml_user_attributes, idme_uuid)
saml_user_attributes.merge({ uuid: idme_uuid, idme_uuid: })
end
def create_user_verification(saml_attributes)
Login::UserVerifier.new(login_type: saml_attributes[:sign_in]&.dig(:service_name),
auth_broker: saml_attributes[:sign_in]&.dig(:auth_broker),
mhv_uuid: saml_attributes[:mhv_credential_uuid],
idme_uuid: saml_attributes[:idme_uuid],
dslogon_uuid: saml_attributes[:edipi],
logingov_uuid: saml_attributes[:logingov_uuid],
icn: saml_attributes[:icn]).perform
end
def add_csp_id_to_mpi(saml_user_attributes, idme_uuid)
return unless saml_user_attributes[:loa][:current] == LOA::THREE
Rails.logger.info("[UserSessionForm] Adding CSP ID to MPI, idme: #{idme_uuid}")
mpi_response = MPI::Service.new.add_person_implicit_search(first_name: saml_user_attributes[:first_name],
last_name: saml_user_attributes[:last_name],
ssn: saml_user_attributes[:ssn],
birth_date: saml_user_attributes[:birth_date],
idme_uuid:)
Rails.logger.warn('[UserSessionForm] Failed Add CSP ID to MPI', idme_uuid:) unless mpi_response.ok?
end
def uuid_from_account(identifier)
return if identifier.blank?
user_account = UserAccount.find_by(icn: identifier)
return unless user_account
idme_uuid_array = user_account.user_verifications.map(&:idme_uuid) +
user_account.user_verifications.map(&:backing_idme_uuid)
idme_uuid_array.compact.first
end
def valid?
errors.add(:session, :invalid) unless session.valid?
errors.add(:user, :invalid) unless user.valid?
errors.add(:user_identity, :invalid) unless @user_identity.valid?
errors.empty?
end
def get_session_errors
@session.errors.add(:uuid, "can't be blank") if @session.uuid.nil?
@session.errors&.full_messages
end
def save
valid? && session.save && user.save && @user_identity.save
end
def persist
if save
[user, session]
else
[nil, nil]
end
end
def errors_message
@errors_message ||= "Login Failed! #{errors_hash[:short_message]}" if errors.any?
end
def errors_hash
ERRORS[:validations_failed] if errors.any?
end
def errors_context
errors_hash.merge(
uuid: @user.uuid,
user: {
valid: @user&.valid?,
errors: @user&.errors&.full_messages
},
session: {
valid: @session.valid? && !@session.uuid.nil?,
errors: get_session_errors
},
identity: {
valid: @user_identity&.valid?,
errors: @user_identity&.errors&.full_messages,
authn_context: @user_identity&.authn_context,
loa: @user_identity&.loa
},
mvi: mvi_context
)
end
def mvi_context
latest_outage = MPI::Configuration.instance.breakers_service.latest_outage
if latest_outage && !latest_outage.ended?
'breakers is closed for MVI'
else
'breakers is open for MVI'
end
end
def error_code
errors_hash[:code] if errors.any?
end
def error_instrumentation_code
"error:#{errors_hash[:tag]}" if errors.any?
end
private
def log_existing_user_warning(saml_uuid, saml_icn)
message = "Couldn't locate existing user after MFA establishment"
Rails.logger.warn("[UserSessionForm] #{message}", saml_uuid:, saml_icn:)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/extract_status.rb
|
# frozen_string_literal: true
require 'vets/model'
require 'digest'
# facility extract statuses, part of PHR refresh.
class ExtractStatus
include Vets::Model
attribute :extract_type, String
attribute :last_updated, Vets::Type::UTCTime
attribute :status, String
attribute :created_on, Vets::Type::UTCTime
attribute :station_number, String
def id
Digest::SHA256.hexdigest(instance_variable_get(:@original_attributes).to_json)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/transaction_notification.rb
|
# frozen_string_literal: true
require 'common/models/concerns/cache_aside'
class TransactionNotification < Common::RedisStore
redis_store REDIS_CONFIG[:transaction_notification][:namespace]
redis_ttl REDIS_CONFIG[:transaction_notification][:each_ttl]
redis_key :transaction_id
attribute :transaction_id, String
validates(:transaction_id, presence: true)
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/secondary_appeal_form.rb
|
# frozen_string_literal: true
class SecondaryAppealForm < ApplicationRecord
validates :guid, :form_id, :form, presence: true
belongs_to :appeal_submission
has_kms_key
has_encrypted :form, key: :kms_key, **lockbox_options
scope :needs_failure_notification, lambda {
where(delete_date: nil, failure_notification_sent_at: nil).where('status LIKE ?', '%error%')
}
scope :with_permanent_error, lambda {
needs_failure_notification.where('status LIKE ?', '%"final_status":true%')
}
scope :incomplete, -> { where(delete_date: nil) }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/eligible_data_class.rb
|
# frozen_string_literal: true
require 'vets/model'
# BlueButton EligibleDataClass
class EligibleDataClass
include Vets::Model
attribute :name, String
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/application_record.rb
|
# frozen_string_literal: true
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
def self.lockbox_options
{
previous_versions: [
{ padding: false },
{ padding: false, master_key: Settings.lockbox.master_key }
]
}
end
def self.descendants_using_encryption
Rails.application.eager_load!
ApplicationRecord.descendants.select do |model|
model = model.name.constantize
model.descendants.empty? &&
model.respond_to?(:lockbox_attributes) &&
model.lockbox_attributes.any?
end
end
def timestamp_attributes_for_update_in_model
kms_key_changed = changed? && changed.include?('encrypted_kms_key')
called_from_kms_encrypted = caller_locations(1, 1)[0].base_label == 'encrypt_kms_keys'
# If update is due to kms key, don't update updated_at
kms_key_changed || called_from_kms_encrypted ? [] : super
end
def valid?(context = nil)
kms_key_changed = changed.include?('encrypted_kms_key')
only_kms_changes = changed.all? { |f| f == 'encrypted_kms_key' || f.include?('_ciphertext') }
# Skip validation ONLY during the case where only KMS fields are being updated
# AND the encrypted_kms_key is present
kms_key_changed && only_kms_changes ? true : super
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user_verification.rb
|
# frozen_string_literal: true
class UserVerification < ApplicationRecord
has_one :deprecated_user_account, dependent: :destroy, required: false
belongs_to :user_account, dependent: nil
has_one :user_credential_email, dependent: :destroy, required: false
validate :single_credential_identifier
validate :backing_uuid_credentials
scope :idme, -> { where.not(idme_uuid: nil) }
scope :logingov, -> { where.not(logingov_uuid: nil) }
scope :mhv, -> { where.not(mhv_uuid: nil) }
scope :dslogon, -> { where.not(dslogon_uuid: nil) }
def self.find_by_type!(type, identifier)
user_verification =
case type
when SAML::User::LOGINGOV_CSID
find_by(logingov_uuid: identifier)
when SAML::User::IDME_CSID
find_by(idme_uuid: identifier)
when SAML::User::MHV_ORIGINAL_CSID
find_by(mhv_uuid: identifier)
when SAML::User::DSLOGON_CSID
find_by(dslogon_uuid: identifier)
end
raise ActiveRecord::RecordNotFound unless user_verification
user_verification
end
def self.find_by_type(type, identifier)
find_by_type!(type, identifier)
rescue ActiveRecord::RecordNotFound
nil
end
def lock!
update!(locked: true)
end
def unlock!
update!(locked: false)
end
def verified?
verified_at.present? && user_account.verified?
end
def credential_type
return SAML::User::IDME_CSID if idme_uuid
return SAML::User::LOGINGOV_CSID if logingov_uuid
return SAML::User::MHV_ORIGINAL_CSID if mhv_uuid
SAML::User::DSLOGON_CSID if dslogon_uuid
end
def credential_identifier
idme_uuid || logingov_uuid || mhv_uuid || dslogon_uuid
end
def backing_credential_identifier
logingov_uuid || idme_uuid || backing_idme_uuid
end
private
# XOR operators between the four credential identifiers mean one, and only one, of these can be
# defined, If two or more are defined, or if none are defined, then a validation error is raised
def single_credential_identifier
unless idme_uuid.present? ^ logingov_uuid.present? ^ mhv_uuid.present? ^ dslogon_uuid.present?
errors.add(:base, 'Must specify one, and only one, credential identifier')
end
end
# All credentials require either an idme_uuid or logingov_uuid, mhv/dslogon credential types
# store the backing idme_uuid as backing_idme_uuid
def backing_uuid_credentials
unless idme_uuid || logingov_uuid || backing_idme_uuid
errors.add(:base, 'Must define either an idme_uuid, logingov_uuid, or backing_idme_uuid')
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/mpi_data.rb
|
# frozen_string_literal: true
require 'mpi/responses/find_profile_response'
require 'mpi/service'
require 'common/models/redis_store'
require 'common/models/concerns/cache_aside'
require 'mpi/constants'
# Facade for MVI. User model delegates MVI correlation id and VA profile (golden record) methods to this class.
# When a profile is requested from one of the delegates it is returned from either a cached response in Redis
# or from the MVI SOAP service.
class MPIData < Common::RedisStore
include Common::CacheAside
REDIS_CONFIG_KEY = :mpi_profile_response
redis_config_key REDIS_CONFIG_KEY
attr_accessor :user_loa3,
:user_icn,
:user_first_name,
:user_last_name,
:user_birth_date,
:user_ssn,
:user_edipi,
:user_logingov_uuid,
:user_idme_uuid,
:user_uuid
# Creates a new MPIData instance for a user identity.
#
# @param user [UserIdentity] the user identity to query MVI for
# @return [MPIData] an instance of this class
def self.for_user(user_identity)
mvi = MPIData.new
mvi.user_loa3 = user_identity.loa3?
mvi.user_icn = user_identity.mhv_icn || user_identity.icn
mvi.user_first_name = user_identity.first_name
mvi.user_last_name = user_identity.last_name
mvi.user_birth_date = user_identity.birth_date
mvi.user_ssn = user_identity.ssn
mvi.user_edipi = user_identity.edipi
mvi.user_logingov_uuid = user_identity.logingov_uuid
mvi.user_idme_uuid = user_identity.idme_uuid
mvi.user_uuid = user_identity.uuid
mvi
end
# A DOD EDIPI (Electronic Data Interchange Personal Identifier) MVI correlation ID
# or nil for users < LOA 3
#
# @return [String] the edipi correlation id
delegate :edipi, to: :profile, allow_nil: true
# @return [Array[String]] multiple edipi correlation ids
delegate :edipis, to: :profile, allow_nil: true
# A ICN (Integration Control Number - generated by the Master Patient Index) MVI correlation ID
# or nil for users < LOA 3
#
# @return [String] the icn correlation id
delegate :icn, to: :profile, allow_nil: true
# A ICN (Integration Control Number - generated by the Master Patient Index) MVI correlation ID
# combined with its Assigning Authority ID. Or nil for users < LOA 3.
#
# @return [String] the icn correlation id with its assigning authority id.
# For example: '12345678901234567^NI^200M^USVHA^P'
#
delegate :icn_with_aaid, to: :profile, allow_nil: true
# A MHV (My HealtheVet) MVI correlation id
# or nil for users < LOA 3
#
# @return [String] the mhv correlation id
delegate :mhv_correlation_id, to: :profile, allow_nil: true
# A VBA (Veterans Benefits Administration) or participant MVI correlation id.
#
# @return [String] the participant id
delegate :participant_id, to: :profile, allow_nil: true
# @return [Array[String]] multiple participant ids
delegate :participant_ids, to: :profile, allow_nil: true
# A BIRLS (Beneficiary Identification and Records Locator System) MVI correlation id.
#
# @return [String] the birls id
delegate :birls_id, to: :profile, allow_nil: true
# @return [Array[String]] multiple birls ids
delegate :birls_ids, to: :profile, allow_nil: true
# An MHV id.
#
# @return [String] the mhv ien id
delegate :mhv_ien, to: :profile, allow_nil: true
# @return [Array[String]] multiple mhv ien ids
delegate :mhv_iens, to: :profile, allow_nil: true
# NPI Correlation ID
#
# @return [String] the NPI id
delegate :npi_id, to: :profile, allow_nil: true
# A Vet360 Correlation ID
#
# @return [String] the Vet360 id
delegate :vet360_id, to: :profile, allow_nil: true
# The search token given in the original MVI 1306 response message
#
# @return [String] the search token
delegate :search_token, to: :profile, allow_nil: true
# A Cerner ID
#
# @return [String] the Cerner id
delegate :cerner_id, to: :profile, allow_nil: true
# The user's Cerner facility ids
#
# @return [Array[String]] the the list of Cerner facility ids
delegate :cerner_facility_ids, to: :profile, allow_nil: true
# Identity theft flag
#
# @return [Boolean] presence or absence of identity theft flag
delegate :id_theft_flag, to: :profile, allow_nil: true
# The person types that the user's profile represents
#
# @return [Array[String]] the list of person types
delegate :person_types, to: :profile, allow_nil: true
# The user's home phone number
#
# @return [String] the home_phone
delegate :home_phone, to: :profile, allow_nil: true
# The profile returned from the MVI service. Either returned from cached response in Redis or the MVI service.
#
# @return [MPI::Models::MviProfile] patient 'golden record' data from MVI
def profile
return nil unless user_loa3
mvi_response&.profile
end
# The status of the last MVI response or not authorized for for users < LOA 3
#
# @return [String] the status of the last MVI response
def status
return :not_authorized unless user_loa3
mvi_response&.status
end
# The error experienced when reaching out to the MVI service.
#
# @return [Common::Exceptions::BackendServiceException]
def error
return Common::Exceptions::Unauthorized.new(source: self.class) unless user_loa3
mvi_response.try(:error)
end
# @return [MPI::Responses::FindProfileResponse] the response returned from MVI
def mvi_response(user_key: get_user_key)
@mvi_response ||= response_from_redis_or_service(user_key:)
end
def mpi_response_is_cached?(user_key: get_user_key)
cached?(key: user_key)
end
# The status of the MPI Add Person Proxy Add call.
# An Orchestrated MVI Search needs to be made to obtain a token before an MPI add person proxy add call is made.
# The cached response is deleted after the response if the call is successful.
#
# @return [MPI::Responses::AddPersonResponse] the response returned from MPI
def add_person_proxy(as_agent: false)
search_response = mpi_service.find_profile_by_identifier(identifier: user_icn,
identifier_type: MPI::Constants::ICN)
if search_response.ok?
orch_search_response = perform_orchestrated_search(search_response)
if orch_search_response.ok?
@mvi_response = orch_search_response
add_person_response = perform_add_person_proxy(orch_search_response, as_agent:)
add_ids(add_person_response) if add_person_response.ok?
add_person_response
else
orch_search_response
end
else
search_response
end
end
private
def perform_orchestrated_search(search_response)
mpi_service.find_profile_by_attributes_with_orch_search(
first_name: search_response.profile.given_names.first,
last_name: search_response.profile.family_name,
birth_date: search_response.profile.birth_date,
ssn: search_response.profile.ssn,
edipi: search_response.profile.edipi
)
end
def perform_add_person_proxy(orch_search_response, as_agent:)
mpi_service.add_person_proxy(last_name: orch_search_response.profile.family_name,
ssn: orch_search_response.profile.ssn,
birth_date: orch_search_response.profile.birth_date,
icn: orch_search_response.profile.icn,
edipi: orch_search_response.profile.edipi,
search_token: orch_search_response.profile.search_token,
first_name: orch_search_response.profile.given_names.first,
as_agent:)
end
def get_user_key
if user_icn.present?
user_icn
elsif user_edipi.present?
user_edipi
elsif user_logingov_uuid.present?
user_logingov_uuid
elsif user_idme_uuid.present?
user_idme_uuid
else
user_uuid
end
end
def find_profile
if user_icn.present?
mpi_service.find_profile_by_identifier(identifier: user_icn, identifier_type: MPI::Constants::ICN)
elsif user_edipi.present?
mpi_service.find_profile_by_edipi(edipi: user_edipi)
elsif user_logingov_uuid.present?
mpi_service.find_profile_by_identifier(identifier: user_logingov_uuid,
identifier_type: MPI::Constants::LOGINGOV_UUID)
elsif user_idme_uuid.present?
mpi_service.find_profile_by_identifier(identifier: user_idme_uuid, identifier_type: MPI::Constants::IDME_UUID)
else
mpi_service.find_profile_by_attributes(first_name: user_first_name,
last_name: user_last_name,
birth_date: user_birth_date,
ssn: user_ssn)
end
end
def add_ids(response)
profile.birls_id = response.parsed_codes[:birls_id].presence
profile.participant_id = response.parsed_codes[:participant_id].presence
delete_cached_response if mvi_response.cache?
end
def response_from_redis_or_service(user_key:)
do_cached_with(key: user_key) do
find_profile
rescue ArgumentError, MPI::Errors::ArgumentError => e
Rails.logger.warn('[MPIData] request error', message: e.message)
return nil
end
end
def delete_cached_response
self.class.delete(get_user_key)
@mvi_response = nil
end
def mpi_service
@service ||= MPI::Service.new
end
def save
saved = super
expire(record_ttl) if saved
saved
end
def record_ttl
if status == :ok
# ensure default ttl is used for 'ok' responses
REDIS_CONFIG[REDIS_CONFIG_KEY][:each_ttl]
else
# assign separate ttl to redis cache for failure responses
REDIS_CONFIG[REDIS_CONFIG_KEY][:failure_ttl]
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/mhv_user_account.rb
|
# frozen_string_literal: true
class MHVUserAccount
include ActiveModel::Model
include ActiveModel::Attributes
attribute :user_profile_id, :string
attribute :premium, :boolean
attribute :champ_va, :boolean
attribute :patient, :boolean
attribute :sm_account_created, :boolean
attribute :message, :string
alias_attribute :id, :user_profile_id
validates :user_profile_id, presence: true
validates :premium, :champ_va, :patient, :sm_account_created, inclusion: { in: [true, false] }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/prescription_documentation.rb
|
# frozen_string_literal: true
require 'active_model'
class PrescriptionDocumentation
attr_reader :html
def initialize(html)
@html = html
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/lcpe_redis.rb
|
# frozen_string_literal: true
require 'common/models/concerns/cache_aside'
require 'gi/lcpe/response'
# Facade for GIDS LCPE data
class LCPERedis < Common::RedisStore
include Common::CacheAside
redis_config_key :lcpe_response
attr_reader :lcpe_type
class ClientCacheStaleError < StandardError; end
def initialize(*, lcpe_type: nil)
@lcpe_type = lcpe_type
super(*)
end
def fresh_version_from(gids_response)
case gids_response.status
when 304
cached_response
else
# Refresh cache with latest version from GIDS
invalidate_cache
do_cached_with(key: lcpe_type) do
GI::LCPE::Response.from(gids_response)
end
end
end
def force_client_refresh_and_cache(gids_response)
v_fresh = gids_response.response_headers['Etag'].match(%r{W/"(\d+)"})[1]
# no need to cache if vets-api cache already has fresh version
cache(lcpe_type, GI::LCPE::Response.from(gids_response)) unless v_fresh == cached_version
raise ClientCacheStaleError
end
def cached_response
self.class.find(lcpe_type)&.response
end
def cached_version
cached_response&.version
end
private
def invalidate_cache
self.class.delete(lcpe_type)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/mhv_opt_in_flag.rb
|
# frozen_string_literal: true
class MHVOptInFlag < ApplicationRecord
belongs_to :user_account, dependent: nil
FEATURES = %w[secure_messaging].freeze
attribute :user_account_id
attribute :feature
validates :feature, presence: true
validates :feature, inclusion: { in: FEATURES }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/health_care_application.rb
|
# frozen_string_literal: true
require 'hca/service'
require 'hca/rate_limited_search'
require 'hca/user_attributes'
require 'hca/enrollment_eligibility/service'
require 'hca/enrollment_eligibility/status_matcher'
require 'mpi/service'
require 'hca/overrides_parser'
require 'kafka/sidekiq/event_bus_submission_job'
class HealthCareApplication < ApplicationRecord
include RetriableConcern
FORM_ID = '10-10EZ'
ACTIVEDUTY_ELIGIBILITY = 'TRICARE'
DISABILITY_THRESHOLD = 50
DD_ZSF_TAGS = [
'service:healthcare-application',
'function: 10-10EZ async form submission'
].freeze
LOCKBOX = Lockbox.new(key: Settings.lockbox.master_key, encode: true)
attr_accessor :user, :google_analytics_client_id, :form
validates(:state, presence: true, inclusion: %w[success error failed pending])
validates(:form_submission_id_string, :timestamp, presence: true, if: :success?)
validate(:long_form_required_fields, on: :create)
validates(:form, presence: true, on: :create)
validate(:form_matches_schema, on: :create)
after_save :send_failure_email, if: :send_failure_email?
after_save :log_async_submission_failure, if: :async_submission_failed?
# @param [Account] user
# @return [Hash]
def self.get_user_identifier(user)
return if user.nil?
{
'icn' => user.icn,
'edipi' => user.edipi
}
end
def success?
state == 'success'
end
def failed?
state == 'failed'
end
def short_form?
form.present? && parsed_form['lastServiceBranch'].blank?
end
def async_submission_failed?
saved_change_to_attribute?(:state) && failed?
end
def email
return nil if form.blank?
parsed_form['email']
end
def send_failure_email?
async_submission_failed? && email.present?
end
def form_id
self.class::FORM_ID
end
def submit_sync
@parsed_form = HCA::OverridesParser.new(parsed_form).override
result = begin
HCA::Service.new(user).submit_form(parsed_form)
rescue Common::Client::Errors::ClientError => e
Rails.logger.error('[10-10EZ] - Error synchronously submitting form', { exception: e, user_loa: user&.loa })
raise Common::Exceptions::BackendServiceException.new(
nil, detail: e.message
)
end
set_result_on_success!(result)
result
rescue
log_sync_submission_failure
raise
end
def process!
prefill_fields
unless valid?
StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.validation_error")
StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.validation_error_short_form") if short_form?
Sentry.set_extras(user_loa: user&.loa)
PersonalInformationLog.create(
data: parsed_form,
error_class: 'HealthCareApplication ValidationError'
)
raise(Common::Exceptions::ValidationErrors, self)
end
save!
send_event_bus_event('received')
if email.present?
submit_async
else
submit_sync
end
end
def self.determine_active_duty(primary_eligibility, veteran)
primary_eligibility == ACTIVEDUTY_ELIGIBILITY && veteran == 'false'
end
def self.determine_non_military(primary_eligibility, veteran, parsed_status)
if parsed_status == HCA::EnrollmentEligibility::Constants::ACTIVEDUTY &&
!determine_active_duty(primary_eligibility, veteran)
HCA::EnrollmentEligibility::Constants::NON_MILITARY
else
parsed_status
end
end
EE_DATA_SELECTED_KEYS = %i[
application_date
enrollment_date
preferred_facility
effective_date
primary_eligibility
priority_group
can_submit_financial_info
].freeze
def self.parsed_ee_data(ee_data, loa3)
if loa3
parsed_status = HCA::EnrollmentEligibility::StatusMatcher.parse(
ee_data[:enrollment_status], ee_data[:ineligibility_reason]
)
parsed_status = determine_non_military(
ee_data[:primary_eligibility], ee_data[:veteran],
parsed_status
)
ee_data.slice(*EE_DATA_SELECTED_KEYS).merge(parsed_status:)
else
{ parsed_status: if ee_data[:enrollment_status].present?
HCA::EnrollmentEligibility::Constants::LOGIN_REQUIRED
else
HCA::EnrollmentEligibility::Constants::NONE_OF_THE_ABOVE
end }
end
end
def self.enrollment_status(icn, loa3)
parsed_ee_data(
HCA::EnrollmentEligibility::Service.new.lookup_user(icn),
loa3
)
end
def self.user_icn(user_attributes)
HCA::RateLimitedSearch.create_rate_limited_searches(user_attributes) unless Settings.mvi_hca.skip_rate_limit
MPI::Service.new.find_profile_by_attributes(first_name: user_attributes.first_name,
last_name: user_attributes.last_name,
birth_date: user_attributes.birth_date,
ssn: user_attributes.ssn)&.profile&.icn
end
def self.user_attributes(form)
form ||= {}
full_name = form['veteranFullName'] || {}
return_val = HCA::UserAttributes.new(
first_name: full_name['first'],
middle_name: full_name['middle'],
last_name: full_name['last'],
birth_date: form['veteranDateOfBirth'],
ssn: form['veteranSocialSecurityNumber'],
gender: form['gender']
)
raise Common::Exceptions::ValidationErrors, return_val unless return_val.valid?
return_val
end
def set_result_on_success!(result)
update!(
state: 'success',
# this is a string because it overflowed the postgres integer limit in one of the tests
form_submission_id_string: result[:formSubmissionId].to_s,
timestamp: result[:timestamp]
)
send_event_bus_event('sent', result[:formSubmissionId].to_s)
end
def form_submission_id
form_submission_id_string&.to_i
end
def parsed_form
@parsed_form ||= form.present? ? JSON.parse(form) : nil
end
def send_event_bus_event(status, next_id = nil)
return unless Flipper.enabled?(:hca_ez_kafka_submission_enabled)
begin
user_icn = user&.icn || self.class.user_icn(self.class.user_attributes(parsed_form))
rescue
# if certain user attributes are missing, we can't get an ICN
user_icn = nil
end
Kafka.submit_event(
icn: user_icn,
current_id: id,
submission_name: 'F1010EZ',
state: status,
next_id:
)
end
private
def long_form_required_fields
return if form.blank? || parsed_form['vaCompensationType'] == 'highDisability'
%w[
maritalStatus
isEnrolledMedicarePartA
lastServiceBranch
lastEntryDate
lastDischargeDate
].each do |attr|
errors.add(:form, "#{attr} can't be null") if parsed_form[attr].nil?
end
end
def prefill_fields
return if user.blank? || !user.loa3?
parsed_form.merge!({
'veteranFullName' => user.full_name_normalized.compact.stringify_keys,
'veteranDateOfBirth' => user.birth_date,
'veteranSocialSecurityNumber' => user.ssn_normalized
}.compact)
end
def submit_async
@parsed_form = HCA::OverridesParser.new(parsed_form).override
HCA::SubmissionJob.perform_async(
self.class.get_user_identifier(user),
HealthCareApplication::LOCKBOX.encrypt(parsed_form.to_json),
id,
google_analytics_client_id
)
self
end
def log_sync_submission_failure
StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.sync_submission_failed")
StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.sync_submission_failed_short_form") if short_form?
log_submission_failure_details
end
def log_async_submission_failure
StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.failed_wont_retry")
StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.failed_wont_retry_short_form") if short_form?
log_submission_failure_details
end
def log_submission_failure_details
return if parsed_form.blank?
send_event_bus_event('error')
PersonalInformationLog.create!(
data: parsed_form,
error_class: 'HealthCareApplication FailedWontRetry'
)
Rails.logger.info(
'[10-10EZ] - HCA total failure',
{
first_initial: parsed_form.dig('veteranFullName', 'first')&.[](0) || 'no initial provided',
middle_initial: parsed_form.dig('veteranFullName', 'middle')&.[](0) || 'no initial provided',
last_initial: parsed_form.dig('veteranFullName', 'last')&.[](0) || 'no initial provided'
}
)
end
def send_failure_email
first_name = parsed_form.dig('veteranFullName', 'first')
template_id = Settings.vanotify.services.health_apps_1010.template_id.form1010_ez_failure_email
api_key = Settings.vanotify.services.health_apps_1010.api_key
salutation = first_name ? "Dear #{first_name}," : ''
metadata =
{
callback_metadata: {
notification_type: 'error',
form_number: FORM_ID,
statsd_tags: DD_ZSF_TAGS
}
}
VANotify::EmailJob.perform_async(email, template_id, { 'salutation' => salutation }, api_key, metadata)
StatsD.increment("#{HCA::Service::STATSD_KEY_PREFIX}.submission_failure_email_sent")
rescue => e
Rails.logger.error('[10-10EZ] - Failure sending Submission Failure Email', { exception: e })
end
def form_matches_schema
return if form.blank?
schema = VetsJsonSchema::SCHEMAS[self.class::FORM_ID]
validation_errors = with_retries('10-10EZ Form Validation') do
JSONSchemer.schema(schema).validate(parsed_form).to_a
end
validation_errors.each do |error|
e = error.symbolize_keys
errors.add(:form, e[:error].to_s)
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/iam_user_identity.rb
|
# frozen_string_literal: true
require 'vets/shared_logging'
# Subclasses the `UserIdentity` model. Adds a unique redis namespace for IAM user identities.
# Like the it's base model it acts as an adapter for the attributes from the IAMSSOeOAuth::Service's
# introspect endpoint.Adds IAM sourced versions of ICN, EDIPI, and SEC ID to pass to the IAMUser model.
#
class IAMUserIdentity < UserIdentity
extend Vets::SharedLogging
extend Identity::Parsers::GCIdsHelper
PREMIUM_LOAS = [2, 3].freeze
UPGRADE_AUTH_TYPES = %w[DSL MHV].freeze
MULTIFACTOR_AUTH_TYPES = %w[IDME LOGINGOV].freeze
IAM_NAMESPACE = 'eb7b724e-bd8c-4dc3-b5fa-30f335938b42'
redis_store REDIS_CONFIG[:iam_user_identity][:namespace]
redis_ttl REDIS_CONFIG[:iam_user_identity][:each_ttl]
redis_key :uuid
attribute :expiration_timestamp, Integer
attribute :iam_edipi, String
attribute :iam_sec_id, String
attribute :iam_mhv_id, String
# MPI::Service uses 'mhv_icn' to query by icn rather than less accurate user traits
alias mhv_icn icn
# Builds an identity instance from the profile returned in the IAM introspect response
#
# @param iam_profile [Hash] the profile of the user, as they are known to the IAM SSOe service.
# @return [IAMUserIdentity] an instance of this class
#
def self.build_from_iam_profile(iam_profile)
loa_level = iam_profile[:fediamassur_level].to_i
iam_auth_n_type = iam_profile[:fediamauth_n_type]
loa_level = 3 if UPGRADE_AUTH_TYPES.include?(iam_auth_n_type) && PREMIUM_LOAS.include?(loa_level)
identity = new(
email: iam_profile[:email],
expiration_timestamp: iam_profile[:exp],
first_name: iam_profile[:given_name],
icn: iam_profile[:fediam_mviicn],
iam_edipi: sanitize_edipi(iam_profile[:fediam_do_dedipn_id]),
iam_sec_id: iam_profile[:fediamsecid],
iam_mhv_id: valid_mhv_id(iam_profile[:fediam_mhv_ien]),
last_name: iam_profile[:family_name],
loa: { current: loa_level, highest: loa_level },
middle_name: iam_profile[:middle_name],
multifactor: multifactor?(loa_level, iam_auth_n_type),
sign_in: { service_name: "oauth_#{iam_auth_n_type}", account_type: iam_profile[:fediamassur_level],
auth_broker: SAML::URLService::BROKER_CODE, client_id: SAML::URLService::MOBILE_CLIENT_ID }
)
identity.set_expire
identity
end
def self.multifactor?(loa_level, auth_type)
loa_level == LOA::THREE && MULTIFACTOR_AUTH_TYPES.include?(auth_type)
end
def set_expire
redis_namespace.expireat(REDIS_CONFIG[:iam_user_identity][:namespace], expiration_timestamp)
end
# Users from IAM don't have a UUID like ID.me, instead we create one from the sec_id and iam_icn.
# It's used for JSON API object serialization, caching (no longer than a session), and debugging.
# The hashed value is not reversible and does not reference any external system or database.
# @return [String] UUID that is unique to this user
#
def uuid
Digest::UUID.uuid_v5(IAM_NAMESPACE, @icn)
end
# Return a single mhv id from a possible comma-separated list value attribute
def self.valid_mhv_id(id_from_profile)
# TODO: For now, log instances of duplicate MHV ID.
# See issue #19971 for consideration of whether to reject access
# to features using this identifier if this happens.
mhv_ids = (id_from_profile == 'NOT_FOUND' ? nil : id_from_profile)
mhv_ids = mhv_ids&.split(',')&.uniq
if mhv_ids&.size.to_i > 1
Rails.logger.warn('[IAMUserIdentity] OAuth: Multiple MHV IDs present', mhv_ien: id_from_profile)
end
mhv_ids&.first
end
private_class_method :valid_mhv_id
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/message_thread_details.rb
|
# frozen_string_literal: true
class MessageThreadDetails < Message
attribute :message_id, Integer
attribute :thread_id, Integer
attribute :folder_id, Integer
attribute :message_body, String
attribute :draft_date, Vets::Type::DateTimeString
attribute :to_date, Vets::Type::DateTimeString
attribute :has_attachments, Bool, default: false
attribute :attachments, Array
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/messaging_signature.rb
|
# frozen_string_literal: true
require 'vets/model'
class MessagingSignature
include Vets::Model
attribute :signature_name, String
attribute :signature_title, String
attribute :include_signature, Bool, default: false
validates :signature_name, :signature_title, :include_signature, presence: true
def to_h
{
signatureName: signature_name,
signatureTitle: signature_title,
includeSignature: include_signature
}
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/datadog_metrics.rb
|
# frozen_string_literal: true
module DatadogMetrics
ALLOWLIST = [
# MR list calls
'mr.labs_and_tests_list',
'mr.care_summaries_and_notes_list',
'mr.vaccines_list',
'mr.allergies_list',
'mr.health_conditions_list',
'mr.vitals_list',
# MR detail calls
'mr.labs_and_tests_details',
'mr.radiology_images_list',
'mr.care_summaries_and_notes_details',
'mr.vaccines_details',
'mr.allergies_details',
'mr.health_conditions_details',
'mr.vitals_details',
# MR download calls
'mr.download_blue_button',
'mr.download_ccd',
'mr.download_sei'
].freeze
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user.rb
|
# frozen_string_literal: true
require 'common/models/base'
require 'common/models/redis_store'
require 'evss/auth_headers'
require 'evss/common_service'
require 'mpi/service'
require 'saml/user'
require 'formatters/date_formatter'
require 'va_profile/configuration'
require 'va_profile/veteran_status/service'
class User < Common::RedisStore
include Authorization
extend Gem::Deprecate
# Defined per issue #6042
ID_CARD_ALLOWED_STATUSES = %w[V1 V3 V6].freeze
redis_store REDIS_CONFIG[:user_b_store][:namespace]
redis_ttl REDIS_CONFIG[:user_b_store][:each_ttl]
redis_key :uuid
validates :uuid, presence: true
attribute :uuid
attribute :last_signed_in, Common::UTCTime # vaafi attributes
attribute :mhv_last_signed_in, Common::UTCTime # MHV audit logging
attribute :user_account_uuid, String
attribute :user_verification_id, Integer
attribute :fingerprint, String
attribute :needs_accepted_terms_of_use, Boolean
attribute :credential_lock, Boolean
attribute :session_handle, String
def initial_sign_in
user_account.created_at
end
def credential_lock
return @credential_lock unless @credential_lock.nil?
@credential_lock = user_verification&.locked
end
def needs_accepted_terms_of_use
return @needs_accepted_terms_of_use unless @needs_accepted_terms_of_use.nil?
@needs_accepted_terms_of_use = user_account&.needs_accepted_terms_of_use?
end
def user_verification
@user_verification ||= UserVerification.find_by(id: user_verification_id)
end
def user_account
@user_account ||= user_verification&.user_account
end
def user_verification_id
@user_verification_id ||= get_user_verification&.id
end
def user_account_uuid
@user_account_uuid ||= user_account&.id
end
# Identity attributes & methods
delegate :authn_context, to: :identity, allow_nil: true
delegate :email, to: :identity, allow_nil: true
delegate :idme_uuid, to: :identity, allow_nil: true
delegate :loa3?, to: :identity, allow_nil: true
delegate :logingov_uuid, to: :identity, allow_nil: true
delegate :mhv_credential_uuid, to: :identity, allow_nil: true
delegate :mhv_icn, to: :identity, allow_nil: true
delegate :multifactor, to: :identity, allow_nil: true
delegate :sign_in, to: :identity, allow_nil: true, prefix: true
delegate :verified_at, to: :identity, allow_nil: true
# Returns a Date string in iso8601 format, eg. '{year}-{month}-{day}'
def birth_date
birth_date = identity.birth_date || birth_date_mpi
Formatters::DateFormatter.format_date(birth_date)
end
def first_name
identity.first_name.presence || first_name_mpi
end
def common_name
[first_name, middle_name, last_name, suffix].compact.join(' ')
end
def edipi
loa3? && identity.edipi.present? ? identity.edipi : edipi_mpi
end
def full_name_normalized
{
first: first_name&.capitalize,
middle: middle_name&.capitalize,
last: last_name&.capitalize,
suffix: normalized_suffix
}
end
def preferred_name
preferred_name_mpi
end
def gender
identity.gender.presence || gender_mpi
end
def icn
identity&.icn || mpi&.icn
end
def loa
identity&.loa || {}
end
def mhv_account_type
identity.mhv_account_type || MHVAccountTypeService.new(self).mhv_account_type
end
def mhv_correlation_id
return unless can_create_mhv_account?
return mhv_user_account.id if mhv_user_account.present?
mpi_mhv_correlation_id if active_mhv_ids&.one?
end
def mhv_user_account(from_cache_only: true)
@mhv_user_account ||= MHV::UserAccount::Creator.new(user_verification:, from_cache_only:).perform
rescue => e
log_mhv_user_account_error(e.message)
nil
end
def middle_name
identity.middle_name.presence || middle_name_mpi
end
def last_name
identity.last_name.presence || last_name_mpi
end
def sec_id
identity&.sec_id || mpi_profile&.sec_id
end
def ssn
identity&.ssn || ssn_mpi
end
def ssn_normalized
ssn&.gsub(/[^\d]/, '')
end
# MPI attributes & methods
delegate :birls_id, to: :mpi
delegate :cerner_id, to: :mpi
delegate :cerner_facility_ids, to: :mpi
delegate :edipis, to: :mpi, prefix: true
delegate :error, to: :mpi, prefix: true
delegate :icn, to: :mpi, prefix: true
delegate :icn_with_aaid, to: :mpi
delegate :id_theft_flag, to: :mpi
delegate :mhv_correlation_id, to: :mpi, prefix: true
delegate :mhv_ien, to: :mpi
delegate :mhv_iens, to: :mpi, prefix: true
delegate :npi_id, to: :mpi
delegate :participant_id, to: :mpi
delegate :participant_ids, to: :mpi, prefix: true
delegate :person_types, to: :mpi
delegate :search_token, to: :mpi
delegate :status, to: :mpi, prefix: true
delegate :vet360_id, to: :mpi
def active_mhv_ids
mpi_profile&.active_mhv_ids&.uniq
end
def address
address = mpi_profile&.address
{
street: address&.street,
street2: address&.street2,
city: address&.city,
state: address&.state,
country: address&.country,
postal_code: address&.postal_code
}
end
def deceased_date
Formatters::DateFormatter.format_date(mpi_profile&.deceased_date)
end
def birth_date_mpi
mpi_profile&.birth_date
end
def edipi_mpi
mpi_profile&.edipi
end
def first_name_mpi
given_names&.first
end
def preferred_name_mpi
mpi_profile&.preferred_names&.first
end
def middle_name_mpi
mpi&.profile&.given_names.to_a[1..]&.join(' ').presence
end
def gender_mpi
mpi_profile&.gender
end
def given_names
mpi_profile&.given_names
end
def home_phone
mpi_profile&.home_phone
end
def last_name_mpi
mpi_profile&.family_name
end
def mhv_account_state
return 'DEACTIVATED' if (mhv_ids.to_a - active_mhv_ids.to_a).any?
return 'MULTIPLE' if active_mhv_ids.to_a.size > 1
return 'NONE' if mhv_correlation_id.blank?
'OK'
end
def mhv_ids
mpi_profile&.mhv_ids
end
def normalized_suffix
mpi_profile&.normalized_suffix
end
def postal_code
mpi&.profile&.address&.postal_code
end
def ssn_mpi
mpi_profile&.ssn
end
def suffix
mpi_profile&.suffix
end
def mpi_profile?
mpi_profile != nil
end
def vha_facility_ids
mpi_profile&.vha_facility_ids || []
end
def vha_facility_hash
mpi_profile&.vha_facility_hash || {}
end
def mpi_gcids
mpi_profile&.full_mvi_ids || []
end
# MPI setter methods
def set_mhv_ids(mhv_id)
mpi_profile.mhv_ids = [mhv_id] + mhv_ids
mpi_profile.active_mhv_ids = [mhv_id] + active_mhv_ids
recache
end
# Other MPI
def validate_mpi_profile
return unless mpi_profile?
raise MPI::Errors::AccountLockedError, 'Death Flag Detected' if mpi_profile.deceased_date
raise MPI::Errors::AccountLockedError, 'Theft Flag Detected' if mpi_profile.id_theft_flag
end
def invalidate_mpi_cache
return unless loa3? && mpi.mpi_response_is_cached? && mpi.mvi_response
mpi.destroy
@mpi = nil
end
# VA Profile attributes
delegate :military_person?, to: :veteran_status
delegate :veteran?, to: :veteran_status
def ssn_mismatch?
return false unless loa3? && identity&.ssn && ssn_mpi
identity.ssn != ssn_mpi
end
def can_access_user_profile?
loa[:current].present?
end
# True if the user has 1 or more treatment facilities, false otherwise
def va_patient?
va_treatment_facility_ids.any?
end
# User's profile contains a list of VHA facility-specific identifiers.
# Facilities in the defined range are treating facilities
def va_treatment_facility_ids
facilities = vha_facility_ids
facilities.select do |f|
Settings.mhv.facility_range.any? { |range| f.to_i.between?(*range) } ||
Settings.mhv.facility_specific.include?(f)
end
end
def can_access_id_card?
loa3? && edipi.present? &&
ID_CARD_ALLOWED_STATUSES.include?(veteran_status.title38_status)
rescue # Default to false for any veteran_status error
false
end
def in_progress_forms
InProgressForm.for_user(self)
end
# Re-caches the MPI response. Use in response to any local changes that
# have been made.
def recache
mpi.cache(uuid, mpi.mvi_response)
end
# destroy both UserIdentity and self
def destroy
identity&.destroy
super
end
def veteran_status
@veteran_status ||= VAProfileRedis::VeteranStatus.for_user(self)
end
%w[profile grants].each do |okta_model_name|
okta_method = "okta_#{okta_model_name}"
define_method(okta_method) do
okta_instance = instance_variable_get(:"@#{okta_method}")
return okta_instance if okta_instance.present?
okta_model = "OktaRedis::#{okta_model_name.camelize}".constantize.with_user(self)
instance_variable_set(:"@#{okta_method}", okta_model)
okta_model
end
end
def identity
@identity ||= UserIdentity.find(uuid)
end
def onboarding
@onboarding ||= VeteranOnboarding.for_user(self)
end
# VeteranOnboarding attributes & methods
delegate :show_onboarding_flow_on_login, to: :onboarding, allow_nil: true
def vet360_contact_info
return nil unless vet360_id.present? || icn.present?
@vet360_contact_info ||= VAProfileRedis::V2::ContactInformation.for_user(self)
end
def va_profile_email
vet360_contact_info&.email&.email_address
end
def vaprofile_contact_info
return nil unless VAProfile::Configuration::SETTINGS.contact_information.enabled && icn.present?
@vaprofile_contact_info ||= VAProfileRedis::V2::ContactInformation.for_user(self)
end
def va_profile_v2_email
vaprofile_contact_info&.email&.email_address
end
def all_emails
the_va_profile_email =
begin
va_profile_email
rescue
nil
end
[the_va_profile_email, email]
.compact_blank
.map(&:downcase)
.uniq
end
def can_access_vet360?
loa3? && icn.present? && vet360_id.present?
rescue # Default to false for any error
false
end
# A user can have served in the military without being a veteran. For example,
# someone can be ex-military by having a discharge status higher than
# 'Other Than Honorable'.
#
# @return [Boolean]
#
def served_in_military?
(edipi.present? && veteran?) || military_person?
end
def flipper_id
email&.downcase || user_account_uuid
end
def relationships
@relationships ||= get_relationships_array
end
def create_mhv_account_async
return unless can_create_mhv_account?
MHV::AccountCreatorJob.perform_async(user_verification_id)
end
def provision_cerner_async(source: nil)
return unless cerner_eligible?
Identity::CernerProvisionerJob.perform_async(icn, source)
end
def cerner_eligible?
loa3? && cerner_id.present?
end
def can_create_mhv_account?
loa3? && !needs_accepted_terms_of_use
end
private
def mpi_profile
return nil unless identity && mpi
mpi.profile
end
def mpi
@mpi ||= MPIData.for_user(identity)
end
# Get user_verification based on login method
# Default is idme, if login method and login uuid are not available,
# fall back to idme
def get_user_verification
case identity_sign_in&.dig(:service_name)
when SAML::User::MHV_ORIGINAL_CSID
return UserVerification.find_by(mhv_uuid: mhv_credential_uuid) if mhv_credential_uuid
when SAML::User::DSLOGON_CSID
return UserVerification.find_by(dslogon_uuid: identity.edipi) if identity.edipi
when SAML::User::LOGINGOV_CSID
return UserVerification.find_by(logingov_uuid:) if logingov_uuid
end
return nil unless idme_uuid
UserVerification.find_by(idme_uuid:) || UserVerification.find_by(backing_idme_uuid: idme_uuid)
end
def get_relationships_array
return unless loa3?
mpi_profile_relationships || bgs_relationships
end
def mpi_profile_relationships
return unless mpi_profile && mpi_profile.relationships.presence
mpi_profile.relationships.map { |relationship| UserRelationship.from_mpi_relationship(relationship) }
end
def bgs_relationships
bgs_dependents = BGS::DependentService.new(self).get_dependents
return unless bgs_dependents.presence && bgs_dependents[:persons]
bgs_dependents[:persons].map { |dependent| UserRelationship.from_bgs_dependent(dependent) }
end
def log_mhv_user_account_error(error_message)
Rails.logger.info('[User] mhv_user_account error', error_message:, icn:)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/triage_team.rb
|
# frozen_string_literal: true
require 'vets/model'
# TriageTeam model
class TriageTeam
include Vets::Model
include RedisCaching
redis_config REDIS_CONFIG[:secure_messaging_store]
attribute :triage_team_id, Integer
attribute :name, String
attribute :relation_type, String
attribute :preferred_team, Bool, default: false
default_sort_by name: :asc
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/evidence_submission_poll_store.rb
|
# frozen_string_literal: true
# RedisStore for caching evidence submission polling to prevent redundant Lighthouse API calls.
# This implements the cache-aside pattern to reduce load on Lighthouse Benefits Documents API.
#
# Cache Strategy:
# - Caches the set of request_ids that have been successfully polled for a given claim
# - TTL of 60 seconds balances freshness with API call reduction
# - Natural invalidation occurs when the set of pending request_ids changes
#
# Usage:
# # Check cache
# cache_record = EvidenceSubmissionPollStore.find(claim_id.to_s)
#
# # Write to cache
# EvidenceSubmissionPollStore.create(
# claim_id: claim_id.to_s,
# request_ids: [123, 456, 789]
# )
#
# See: https://depo-platform-documentation.scrollhelp.site/developer-docs/how-to-guide-caching-with-redis-namespace-in-vets-
class EvidenceSubmissionPollStore < Common::RedisStore
redis_store REDIS_CONFIG[:evidence_submission_poll_store][:namespace]
redis_ttl REDIS_CONFIG[:evidence_submission_poll_store][:each_ttl]
redis_key :claim_id
attribute :claim_id, String
attribute :request_ids, Array[Integer]
validates :claim_id, :request_ids, presence: true
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user_relationship.rb
|
# frozen_string_literal: true
class UserRelationship
attr_accessor :first_name, :last_name, :birth_date, :ssn,
:gender, :veteran_status, :participant_id, :icn
PERSON_TYPE_VETERAN = 'VET'
# Initializer with a single 'person' from a BGS get_dependents call
def self.from_bgs_dependent(bgs_dependent)
user_relationship = new
# Profile attributes
user_relationship.first_name = bgs_dependent[:first_name]
user_relationship.last_name = bgs_dependent[:last_name]
user_relationship.birth_date = Formatters::DateFormatter.format_date(bgs_dependent[:date_of_birth])
user_relationship.ssn = bgs_dependent[:ssn]
user_relationship.gender = bgs_dependent[:gender]
user_relationship.veteran_status = bgs_dependent[:veteran_indicator] == 'Y'
# ID attributes
user_relationship.participant_id = bgs_dependent[:ptcpnt_id]
user_relationship
end
# Initializer with a single 'person' from an MPI response RelationshipHolder stanza
def self.from_mpi_relationship(mpi_relationship)
user_relationship = new
# Profile attributes
user_relationship.first_name = mpi_relationship.given_names&.first
user_relationship.last_name = mpi_relationship.family_name
user_relationship.birth_date = Formatters::DateFormatter.format_date(mpi_relationship.birth_date)
user_relationship.ssn = mpi_relationship.ssn
user_relationship.gender = mpi_relationship.gender
user_relationship.veteran_status = mpi_relationship.person_types.include? PERSON_TYPE_VETERAN
# ID attributes
user_relationship.icn = mpi_relationship.icn
user_relationship.participant_id = mpi_relationship.participant_id
user_relationship
end
# Sparse hash to serialize to frontend
def to_hash
{
first_name:,
last_name:,
birth_date:
}
end
# Full MPI Profile object
def get_full_attributes
user_identity = build_user_identity
MPIData.for_user(user_identity)
end
private
def build_user_identity
UserIdentity.new(
uuid: SecureRandom.uuid,
first_name: first_name.to_s,
last_name: last_name.to_s,
birth_date: birth_date.to_s,
gender: gender.to_s,
ssn: ssn.to_s,
icn: icn.to_s,
mhv_icn: icn.to_s,
loa: {
current: LOA::THREE,
highest: LOA::THREE
}
)
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/base.rb
|
# frozen_string_literal: true
require 'vets/model'
module BGSDependentsV2
class Base
include Vets::Model
MILITARY_POST_OFFICE_TYPE_CODES = %w[APO DPO FPO].freeze
# Gets the person's address based on the lives with veteran flag
#
# @param dependents_application [Hash] the submitted form information
# @param lives_with_vet [Boolean] does live with veteran indicator
# @param alt_address [Hash] alternate address
# @return [Hash] address information
#
def dependent_address(dependents_application:, lives_with_vet:, alt_address:)
return dependents_application.dig('veteran_contact_information', 'veteran_address') if lives_with_vet
alt_address
end
def relationship_type(info)
if info['dependent_type']
return { participant: 'Guardian', family: 'Other' } if info['dependent_type'] == 'DEPENDENT_PARENT'
{
participant: info['dependent_type'].capitalize.gsub('_', ' '),
family: info['dependent_type'].capitalize.gsub('_', ' ')
}
end
end
def serialize_dependent_result(
participant,
participant_relationship_type,
family_relationship_type,
optional_fields = {}
)
{
vnp_participant_id: participant[:vnp_ptcpnt_id],
participant_relationship_type_name: participant_relationship_type,
family_relationship_type_name: family_relationship_type,
begin_date: optional_fields[:begin_date],
end_date: optional_fields[:end_date],
event_date: optional_fields[:event_date],
marriage_state: optional_fields[:marriage_state],
marriage_city: optional_fields[:marriage_city],
marriage_country: optional_fields[:marriage_country],
divorce_state: optional_fields[:divorce_state],
divorce_city: optional_fields[:divorce_city],
divorce_country: optional_fields[:divorce_country],
marriage_termination_type_code: optional_fields[:marriage_termination_type_code],
living_expenses_paid_amount: optional_fields[:living_expenses_paid],
child_prevly_married_ind: optional_fields[:child_prevly_married_ind],
guardian_particpant_id: optional_fields[:guardian_particpant_id],
type: optional_fields[:type],
dep_has_income_ind: optional_fields[:dep_has_income_ind]
}
end
def create_person_params(proc_id, participant_id, payload)
{
vnp_proc_id: proc_id,
vnp_ptcpnt_id: participant_id,
first_nm: payload['first'],
middle_nm: payload['middle'],
last_nm: payload['last'],
suffix_nm: payload['suffix'],
brthdy_dt: format_date(payload['birth_date']),
birth_cntry_nm: payload['place_of_birth_country'],
birth_state_cd: payload['place_of_birth_state'],
birth_city_nm: payload['place_of_birth_city'],
file_nbr: payload['va_file_number'],
ssn_nbr: payload['ssn'],
death_dt: format_date(payload['death_date']),
ever_maried_ind: payload['ever_married_ind'],
vet_ind: payload['vet_ind'],
martl_status_type_cd: payload['martl_status_type_cd'],
vnp_srusly_dsabld_ind: payload['not_self_sufficient']
}
end
# Converts a string "00/00/0000" to standard iso8601 format
#
# @return [String] formatted date
#
def format_date(date)
return nil if date.nil?
DateTime.parse("#{date} 12:00:00").to_time.iso8601
end
def generate_address(address)
return if address.blank?
# BGS will throw an error if we pass in a military postal code in for state
if MILITARY_POST_OFFICE_TYPE_CODES.include?(address['city'])
address['military_postal_code'] = address.delete('state')
address['military_post_office_type_code'] = address.delete('city')
end
adjust_address_lines_for!(address: address['veteran_address']) if address['veteran_address']
adjust_address_lines_for!(address:)
adjust_country_name_for!(address:)
address
end
# BGS will not accept address lines longer than 20 characters
def adjust_address_lines_for!(address:)
return if address.blank?
all_lines = "#{address['street']} #{address['street2']} #{address['street3']}"
new_lines = all_lines.gsub(/\s+/, ' ').scan(/.{1,19}(?: |$)/).map(&:strip)
address['address_line1'] = new_lines[0]
address['address_line2'] = new_lines[1]
address['address_line3'] = new_lines[2]
end
# rubocop:disable Metrics/MethodLength
# This method converts ISO 3166-1 Alpha-3 country codes to ISO 3166-1 country names.
def adjust_country_name_for!(address:)
return if address.blank?
return if address['country'] == 'USA'
country_name = address['country']
return if country_name.blank? || country_name.size != 3
# The ISO 3166-1 country name for GBR exceeds BIS's (formerly, BGS) 50 char limit. No other country name exceeds
# this limit. For GBR, BIS expects "United Kingdom" instead. BIS has suggested using one of their web services
# to get the correct country names, rather than relying on the IsoCountryCodes gem below. It may be worth
# pursuing that some day. Until then, the following short-term improvement suffices.
# we are now using a short term fix for special country names that are different from IsoCountryCodes in BIS.
special_country_names = { 'USA' => 'USA', 'BOL' => 'Bolivia', 'BIH' => 'Bosnia-Herzegovina', 'BRN' => 'Brunei',
'CPV' => 'Cape Verde', 'COG' => "Congo, People's Republic of",
'COD' => 'Congo, Democratic Republic of', 'CIV' => "Cote d'Ivoire",
'CZE' => 'Czech Republic', 'PRK' => 'North Korea', 'KOR' => 'South Korea',
'LAO' => 'Laos', 'MKD' => 'Macedonia', 'MDA' => 'Moldavia', 'RUS' => 'Russia',
'KNA' => 'St. Kitts', 'LCA' => 'St. Lucia', 'STP' => 'Sao-Tome/Principe',
'SCG' => 'Serbia', 'SYR' => 'Syria', 'TZA' => 'Tanzania',
'GBR' => 'United Kingdom', 'VEN' => 'Venezuela', 'VNM' => 'Vietnam',
'YEM' => 'Yemen Arab Republic' }
address['country'] =
if country_name.to_s == 'TUR'
address['city'].to_s.downcase == 'adana' ? 'Turkey (Adana only)' : 'Turkey (except Adana)'
elsif special_country_names[country_name.to_s].present?
special_country_names[country_name.to_s]
else
IsoCountryCodes.find(country_name).name
end
address
end
# rubocop:enable Metrics/MethodLength
# rubocop:disable Metrics/MethodLength
def create_address_params(proc_id, participant_id, payload)
address = generate_address(payload)
if address['military_postal_code'].present? || address['country'] == 'USA'
frgn_postal_code = nil
state = address['state']
zip_prefix_nbr = address['postal_code']
else
frgn_postal_code = address['postal_code']
state = nil
zip_prefix_nbr = nil
end
{
efctv_dt: Time.current.iso8601,
vnp_ptcpnt_id: participant_id,
vnp_proc_id: proc_id,
ptcpnt_addrs_type_nm: 'Mailing',
shared_addrs_ind: 'N',
addrs_one_txt: address['address_line1'],
addrs_two_txt: address['address_line2'],
addrs_three_txt: address['address_line3'],
city_nm: address['city'],
cntry_nm: address['country'],
postal_cd: state,
frgn_postal_cd: frgn_postal_code,
mlty_postal_type_cd: address['military_postal_code'],
mlty_post_office_type_cd: address['military_post_office_type_code'],
zip_prefix_nbr:,
prvnc_nm: address['state'],
email_addrs_txt: payload['email_address']
}
end
# rubocop:enable Metrics/MethodLength
def formatted_boolean(bool_attribute)
return nil if bool_attribute.nil?
bool_attribute ? 'Y' : 'N'
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/veteran.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class Veteran < Base
attribute :participant_id, String
attribute :ssn, String
attribute :first_name, String
attribute :middle_name, String
attribute :last_name, String
def initialize(proc_id, user) # rubocop:disable Lint/MissingSuper
@proc_id = proc_id
@user = user
assign_attributes
end
def formatted_params(payload)
dependents_application = payload['dependents_application']
vet_info = [
*payload['veteran_information'],
['first', first_name],
['middle', middle_name],
['last', last_name],
*dependents_application['veteran_contact_information'],
*dependents_application.dig('veteran_contact_information', 'veteran_address'),
%w[vet_ind Y]
]
if dependents_application['current_marriage_information']
vet_info << ['martl_status_type_cd', marital_status(dependents_application)]
end
vet_info.to_h
end
# rubocop:disable Metrics/MethodLength
def veteran_response(participant, address, claim_info)
{
vnp_participant_id: participant[:vnp_ptcpnt_id],
first_name:,
last_name:,
vnp_participant_address_id: address[:vnp_ptcpnt_addrs_id],
file_number: claim_info[:va_file_number],
address_line_one: address[:addrs_one_txt],
address_line_two: address[:addrs_two_txt],
address_line_three: address[:addrs_three_txt],
address_country: address[:cntry_nm],
address_state_code: address[:postal_cd],
address_city: address[:city_nm],
address_zip_code: address[:zip_prefix_nbr],
address_type: address[:address_type],
mlty_postal_type_cd: address[:mlty_postal_type_cd],
mlty_post_office_type_cd: address[:mlty_post_office_type_cd],
foreign_mail_code: address[:frgn_postal_cd],
type: 'veteran',
benefit_claim_type_end_product: claim_info[:claim_type_end_product],
regional_office_number: claim_info[:regional_office_number],
location_id: claim_info[:location_id],
net_worth_over_limit_ind: claim_info[:net_worth_over_limit_ind]
}
end
# rubocop:enable Metrics/MethodLength
private
def assign_attributes
@participant_id = @user.participant_id
@ssn = @user.ssn
@first_name = @user.first_name
@middle_name = @user.middle_name
@last_name = @user.last_name
end
def marital_status(dependents_application)
spouse_lives_with_vet = dependents_application.dig('does_live_with_spouse', 'spouse_does_live_with_veteran')
return nil if spouse_lives_with_vet.nil?
spouse_lives_with_vet ? 'Married' : 'Separated'
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/adult_child_attending_school.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class AdultChildAttendingSchool < Base
# The AdultChildAttendingSchool class represents a person including name and address info
#
# @!attribute first
# @return [String] the person's first name
# @!attribute middle
# @return [String] the person's middle name
# @!attribute last
# @return [String] the person's last name
# @!attribute suffix
# @return [String] the person's name suffix
# @!attribute ssn
# @return [String] the person's social security number
# @!attribute birth_date
# @return [String] the person's birth date
# @!attribute ever_married_ind
# @return [String] Y/N indicates whether the person has ever been married
#
attribute :first, String
attribute :middle, String
attribute :last, String
attribute :suffix, String
attribute :ssn, String
attribute :birth_date, String
attribute :ever_married_ind, String
attribute :dependent_income, String
attribute :relationship_to_student, String
validates :first, presence: true
validates :last, presence: true
STUDENT_STATUS = {
'stepchild' => 'Stepchild',
'biological' => 'Biological',
'adopted' => 'Adopted Child'
}.freeze
def initialize(dependents_application) # rubocop:disable Lint/MissingSuper
@source = dependents_application
@ssn = @source['ssn']
@full_name = @source['full_name']
@birth_date = @source['birth_date']
@was_married = @source['was_married']
@ever_married_ind = formatted_boolean(@was_married)
@dependent_income = dependent_income
@first = @full_name['first']
@middle = @full_name['middle']
@last = @full_name['last']
@suffix = @full_name['suffix']
@relationship_to_student = STUDENT_STATUS[@source['relationship_to_student']]
end
# Sets a hash with AdultChildAttendingSchool attributes
#
# @return [Hash] AdultChildAttendingSchool attributes including name and address info
#
def format_info
attributes.with_indifferent_access
end
# Sets a hash with the student's address based on the submitted form information
#
# @return [Hash] the student's address
#
def address
@source['address']
end
def dependent_income
if @source['student_income'] == 'NA'
nil
else
@source['student_income']
end
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/divorce.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class Divorce < Base
def initialize(divorce_info) # rubocop:disable Lint/MissingSuper
@divorce_info = divorce_info
end
def format_info
{
divorce_state: @divorce_info.dig('divorce_location', 'location', 'state'),
divorce_city: @divorce_info.dig('divorce_location', 'location', 'city'),
divorce_country: @divorce_info.dig('divorce_location', 'location', 'country'),
marriage_termination_type_code: @divorce_info['reason_marriage_ended'],
end_date: format_date(@divorce_info['date']),
vet_ind: 'N',
ssn: @divorce_info['ssn'],
birth_date: @divorce_info['birth_date'],
type: 'divorce',
spouse_income:
}.merge(@divorce_info['full_name']).with_indifferent_access
end
def spouse_income
if @divorce_info['spouse_income'] == 'NA'
nil
else
@divorce_info['spouse_income']
end
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/child.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class Child < Base
# The Child class represents a veteran's dependent/child including name, address, and birth info
#
# @!attribute ssn
# @return [String] the person's social security number
# @!attribute first
# @return [String] the person's first name
# @!attribute middle
# @return [String] the person's middle name
# @!attribute last
# @return [String] the person's last name
# @!attribute suffix
# @return [String] the person's name suffix
# @!attribute ever_married_ind
# @return [String] Y/N indicates whether the person has ever been married
# @!attribute place_of_birth_city
# @return [String] city where child was born
# @!attribute place_of_birth_state
# @return [String] state where child was born
# @!attribute reason_marriage_ended
# @return [String] reason child marriage ended
# @!attribute family_relationship_type
# @return [String] family relationship type: Biological/Stepchild/Adopted Child/Other
# @!attribute child_income
# @return [String] did this child have income in the last 365 days
#
attribute :ssn, String
attribute :first, String
attribute :middle, String
attribute :last, String
attribute :suffix, String
attribute :birth_date, String
attribute :ever_married_ind, String
attribute :place_of_birth_city, String
attribute :place_of_birth_state, String
attribute :place_of_birth_country, String
attribute :reason_marriage_ended, String
attribute :family_relationship_type, String
attribute :child_income, String
attribute :not_self_sufficient, String
CHILD_STATUS = {
'stepchild' => 'Stepchild',
'biological' => 'Biological',
'adopted' => 'Adopted Child',
'disabled' => 'Other',
'child_under18' => 'Other',
'child_over18_in_school' => 'Other'
}.freeze
# These are required fields in BGS
validates :first, presence: true
validates :last, presence: true
def initialize(child_info) # rubocop:disable Lint/MissingSuper
@child_info = child_info
assign_attributes
end
# Sets a hash with child attributes
#
# @return [Hash] child attributes including name, address and birth info
#
def format_info
attributes.with_indifferent_access
end
# Sets a hash with address information based on the submitted form information
#
# @param dependents_application [Hash] the submitted form information
# @return [Hash] child address
#
def address(dependents_application)
dependent_address(
dependents_application:,
lives_with_vet: @child_info['does_child_live_with_you'],
alt_address: @child_info['address']
)
end
private
def assign_attributes
@ssn = @child_info['ssn']
@birth_date = @child_info['birth_date']
@family_relationship_type = child_status
@place_of_birth_country = place_of_birth['country']
@place_of_birth_state = place_of_birth['state']
@place_of_birth_city = place_of_birth['city']
@reason_marriage_ended = reason_marriage_ended
@ever_married_ind = marriage_indicator
@child_income = child_income
@not_self_sufficient = formatted_boolean(@child_info['does_child_have_permanent_disability'])
@first = @child_info['full_name']['first']
@middle = @child_info['full_name']['middle']
@last = @child_info['full_name']['last']
@suffix = @child_info['full_name']['suffix']
end
def place_of_birth
@child_info.dig('birth_location', 'location')
end
def child_status
if @child_info['is_biological_child']
'Biological'
elsif @child_info['relationship_to_child']
# adopted, stepchild
CHILD_STATUS[@child_info['relationship_to_child']&.key(true)] || 'Other'
elsif @child_info['child_status']
# v1 format - included in case of legacy data
# adopted, stepchild, child_under18, child_over18_in_school, disabled
CHILD_STATUS[@child_info['child_status']&.key(true)] || 'Other'
else
Rails.logger.warn(
'BGSDependentsV2::Child: Unable to determine child status', {
relationship_to_child: @child_info['relationship_to_child'],
child_status: @child_info['child_status'],
is_biological_child: @child_info['is_biological_child']
}
)
'Other'
end
end
def marriage_indicator
@child_info['has_child_ever_been_married'] ? 'Y' : 'N'
end
def reason_marriage_ended
@child_info['marriage_end_reason']
end
def child_income
if @child_info['income_in_last_year'] == 'NA'
nil
else
@child_info['income_in_last_year']
end
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/vnp_benefit_claim.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class VnpBenefitClaim
VNP_BENEFIT_CREATE_PARAMS = {
status_type_cd: 'CURR',
svc_type_cd: 'CP',
pgm_type_cd: 'COMP',
bnft_claim_type_cd: '130DPNEBNADJ',
atchms_ind: 'N'
}.freeze
def initialize(proc_id, veteran)
@veteran = veteran
@proc_id = proc_id
end
def create_params_for_686c
{
vnp_proc_id: @proc_id,
claim_rcvd_dt: Time.current.iso8601,
ptcpnt_clmant_id: @veteran[:vnp_participant_id],
ptcpnt_mail_addrs_id: @veteran[:vnp_participant_address_id],
vnp_ptcpnt_vet_id: @veteran[:vnp_participant_id],
claim_jrsdtn_lctn_id: @veteran[:location_id],
intake_jrsdtn_lctn_id: @veteran[:location_id],
net_worth_over_limit_ind: @veteran[:net_worth_over_limit_ind]
}.merge(VNP_BENEFIT_CREATE_PARAMS)
end
def update_params_for_686c(vnp_benefit_claim_record, benefit_claim_record)
{
vnp_proc_id: vnp_benefit_claim_record[:vnp_proc_id],
vnp_bnft_claim_id: vnp_benefit_claim_record[:vnp_benefit_claim_id],
vnp_ptcpnt_vet_id: @veteran[:vnp_participant_id],
end_prdct_type_cd: @veteran[:benefit_claim_type_end_product],
bnft_claim_type_cd: benefit_claim_record[:claim_type_code],
claim_rcvd_dt: Time.current.iso8601,
bnft_claim_id: benefit_claim_record[:benefit_claim_id],
intake_jrsdtn_lctn_id: vnp_benefit_claim_record[:intake_jrsdtn_lctn_id],
claim_jrsdtn_lctn_id: vnp_benefit_claim_record[:claim_jrsdtn_lctn_id],
pgm_type_cd: benefit_claim_record[:program_type_code],
ptcpnt_clmant_id: vnp_benefit_claim_record[:participant_claimant_id],
status_type_cd: benefit_claim_record[:status_type_code],
svc_type_cd: 'CP',
net_worth_over_limit_ind: @veteran[:net_worth_over_limit_ind]
}.merge
end
def vnp_benefit_claim_response(vnp_benefit_claim)
{
vnp_proc_id: vnp_benefit_claim[:vnp_proc_id],
vnp_benefit_claim_id: vnp_benefit_claim[:vnp_bnft_claim_id],
vnp_benefit_claim_type_code: vnp_benefit_claim[:bnft_claim_type_cd],
claim_jrsdtn_lctn_id: vnp_benefit_claim[:claim_jrsdtn_lctn_id],
intake_jrsdtn_lctn_id: vnp_benefit_claim[:intake_jrsdtn_lctn_id],
participant_claimant_id: vnp_benefit_claim[:ptcpnt_clmant_id]
}
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/child_marriage.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class ChildMarriage < Base
def initialize(child_marriage) # rubocop:disable Lint/MissingSuper
@child_marriage = child_marriage
end
def format_info
{
event_date: @child_marriage['date_married'],
ssn: @child_marriage['ssn'],
birth_date: @child_marriage['birth_date'],
ever_married_ind: 'Y',
dependent_income:
}.merge(@child_marriage['full_name']).with_indifferent_access
end
def dependent_income
if @child_marriage['dependent_income'] == 'NA'
nil
else
@child_marriage['dependent_income']
end
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/step_child.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class StepChild < Base
EXPENSE_PAID_CONVERTER = { 'Half' => '.5', 'More than half' => '.75', 'Less than half' => '.25' }.freeze
def initialize(stepchild_info) # rubocop:disable Lint/MissingSuper
@stepchild_info = stepchild_info
end
def format_info
{
living_expenses_paid: EXPENSE_PAID_CONVERTER[@stepchild_info['living_expenses_paid']],
lives_with_relatd_person_ind: 'N',
ssn: @stepchild_info['ssn'],
birth_date: @stepchild_info['birth_date']
}.merge(@stepchild_info['full_name']).with_indifferent_access
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/child_school.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class ChildSchool < Base
attribute :last_term_school_information, Hash
attribute :school_information, Hash
attribute :program_information, Hash
attribute :current_term_dates, Hash
def initialize(proc_id, vnp_participant_id, student = nil) # rubocop:disable Lint/MissingSuper
@proc_id = proc_id
@vnp_participant_id = vnp_participant_id
@student = student
assign_attributes(student)
end
# rubocop:disable Metrics/MethodLength
def params_for_686c
{
vnp_proc_id: @proc_id,
vnp_ptcpnt_id: @vnp_participant_id,
last_term_start_dt: format_date(school_information&.dig('last_term_school_information', 'term_begin')),
last_term_end_dt: format_date(school_information&.dig('last_term_school_information', 'date_term_ended')),
prev_hours_per_wk_num: nil,
prev_sessns_per_wk_num: nil,
prev_school_nm: nil,
prev_school_cntry_nm: nil,
prev_school_addrs_one_txt: nil,
prev_school_addrs_two_txt: nil,
prev_school_addrs_three_txt: nil,
prev_school_city_nm: nil,
prev_school_postal_cd: nil,
prev_school_addrs_zip_nbr: nil,
curnt_school_nm: school_information&.dig('name'),
curnt_school_addrs_one_txt: nil,
curnt_school_addrs_two_txt: nil,
curnt_school_addrs_three_txt: nil,
curnt_school_postal_cd: nil,
curnt_school_city_nm: nil,
curnt_school_addrs_zip_nbr: nil,
curnt_school_cntry_nm: nil,
course_name_txt: nil,
curnt_sessns_per_wk_num: nil,
curnt_hours_per_wk_num: nil,
school_actual_expctd_start_dt: school_information&.dig('current_term_dates', 'expected_student_start_date'),
school_term_start_dt: format_date(school_information&.dig('current_term_dates', 'official_school_start_date')),
gradtn_dt: format_date(school_information&.dig('current_term_dates', 'expected_graduation_date')),
full_time_studnt_type_cd: nil,
part_time_school_subjct_txt: nil
}
end
# rubocop:enable Metrics/MethodLength
private
def assign_attributes(data)
@last_term_school_information = data['last_term_school_information']
@school_information = data['school_information']
@program_information = data['program_information']
@current_term_dates = data['current_term_dates']
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/marriage_history.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class MarriageHistory < Base
def initialize(former_spouse) # rubocop:disable Lint/MissingSuper
@former_spouse = former_spouse
@start_source = @former_spouse.dig('start_location', 'location')
@end_source = @former_spouse.dig('end_location', 'location')
end
def format_info
{
start_date: @former_spouse['start_date'],
end_date: @former_spouse['end_date'],
marriage_country: @start_source['country'],
marriage_state: @start_source['state'],
marriage_city: @start_source['city'],
divorce_country: @end_source['country'],
divorce_state: @end_source['state'],
divorce_city: @end_source['city'],
marriage_termination_type_code: @former_spouse['reason_marriage_ended']
}.merge(@former_spouse['full_name']).with_indifferent_access
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/death.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class Death < Base
def initialize(death_info) # rubocop:disable Lint/MissingSuper
@death_info = death_info
end
def format_info
dependent_type = relationship_type(@death_info)
info = {
death_date: format_date(@death_info['dependent_death_date']),
ssn: @death_info['ssn'],
birth_date: @death_info['birth_date'],
vet_ind: 'N',
dependent_income:
}
info['marriage_termination_type_code'] = 'Death' if dependent_type[:family] == 'Spouse'
info.merge(@death_info['full_name']).with_indifferent_access
end
def dependent_income
if @death_info['deceased_dependent_income'] == 'NA'
nil
else
@death_info['deceased_dependent_income']
end
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/relationship.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class Relationship < Base
def initialize(proc_id) # rubocop:disable Lint/MissingSuper
@proc_id = proc_id
end
def params_for_686c(participant_a_id, dependent)
{
vnp_proc_id: @proc_id,
vnp_ptcpnt_id_a: participant_a_id,
vnp_ptcpnt_id_b: dependent[:vnp_participant_id],
ptcpnt_rlnshp_type_nm: dependent[:participant_relationship_type_name],
family_rlnshp_type_nm: dependent[:family_relationship_type_name],
event_dt: format_date(dependent[:event_date]),
begin_dt: format_date(dependent[:begin_date]),
end_dt: format_date(dependent[:end_date]),
mthly_support_from_vet_amt: dependent[:living_expenses_paid_amount],
child_prevly_married_ind: dependent[:child_prevly_married_ind],
dep_has_income_ind: dependent[:dep_has_income_ind]
}.merge(marriage_params(dependent))
end
private
def marriage_params(dependent)
{
marage_cntry_nm: dependent[:marriage_country],
marage_state_cd: dependent[:marriage_state],
marage_city_nm: dependent[:marriage_city],
marage_trmntn_cntry_nm: dependent[:divorce_country],
marage_trmntn_state_cd: dependent[:divorce_state],
marage_trmntn_city_nm: dependent[:divorce_city],
marage_trmntn_type_cd: dependent[:marriage_termination_type_code]
}
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/spouse.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class Spouse < Base
# The Spouse class represents a person including name, address, and marital status info
#
# @!attribute ssn
# @return [String] the person's social security number
# @!attribute first
# @return [String] the person's first name
# @!attribute middle
# @return [String] the person's middle name
# @!attribute last
# @return [String] the person's last name
# @!attribute suffix
# @return [String] the person's name suffix
# @!attribute vet_ind
# @return [String] Y/N indicates whether the person is a veteran
# @!attribute birth_date
# @return [String] the person's birth date
# @!attribute address
# @return [Hash] the person's address
# @!attribute va_file_number
# @return [String] the person's va file number
# @!attribute ever_married_ind
# @return [String] Y/N indicates whether the person has ever been married
# @!attribute martl_status_type_cd
# @return [String] marital status type: Married, Divorced, Widowed, Separated, Never Married
# @!attribute spouse_income
# @return [String] did this spouse have income in the last 365 days
#
attribute :ssn, String
attribute :first, String
attribute :middle, String
attribute :last, String
attribute :suffix, String
attribute :vet_ind, String
attribute :birth_date, String
attribute :address, Hash
attribute :va_file_number, String
attribute :ever_married_ind, String
attribute :martl_status_type_cd, String
attribute :spouse_income, String
def initialize(dependents_application) # rubocop:disable Lint/MissingSuper
@dependents_application = dependents_application
@spouse_information = @dependents_application['spouse_information']
assign_attributes
end
# Sets a hash with spouse attributes
#
# @return [Hash] spouse attributes including name, address and marital info
#
def format_info
attributes.with_indifferent_access
end
private
def assign_attributes
@ssn = @spouse_information['ssn']
@birth_date = @spouse_information['birth_date']
@ever_married_ind = 'Y'
@martl_status_type_cd = marital_status
@vet_ind = spouse_is_veteran
@address = spouse_address
@spouse_income = spouse_income
@first = @spouse_information['full_name']['first']
@middle = @spouse_information['full_name']['middle']
@last = @spouse_information['full_name']['last']
@suffix = @spouse_information['full_name']['suffix']
@va_file_number = @spouse_information['va_file_number'] if spouse_is_veteran == 'Y'
end
def lives_with_vet
@dependents_application['does_live_with_spouse']['spouse_does_live_with_veteran']
end
def spouse_is_veteran
@spouse_information['is_veteran'] ? 'Y' : 'N'
end
def marital_status
lives_with_vet ? 'Married' : 'Separated'
end
def spouse_income
if @dependents_application['does_live_with_spouse']['spouse_income'] == 'NA'
nil
else
@dependents_application['does_live_with_spouse']['spouse_income']
end
end
def spouse_address
dependent_address(
dependents_application: @dependents_application,
lives_with_vet: @dependents_application['does_live_with_spouse']['spouse_does_live_with_veteran'],
alt_address: @dependents_application.dig('does_live_with_spouse', 'address')
)
end
# temporarily not used until rbps can handle it in the payload
def marriage_method_name
@dependents_application.dig('current_marriage_information', 'type_of_marriage')
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/child_stopped_attending_school.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class ChildStoppedAttendingSchool < Base
def initialize(child_info) # rubocop:disable Lint/MissingSuper
@child_info = child_info
end
def format_info
{
event_date: @child_info['date_child_left_school'],
ssn: @child_info['ssn'],
birth_date: @child_info['birth_date'],
dependent_income:
}.merge(@child_info['full_name']).with_indifferent_access
end
def dependent_income
if @child_info['dependent_income'] == 'NA'
nil
else
@child_info['dependent_income']
end
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs_dependents_v2/child_student.rb
|
# frozen_string_literal: true
module BGSDependentsV2
class ChildStudent < Base
attribute :student_address_marriage_tuition, Hash
attribute :student_earnings_from_school_year, Hash
attribute :student_networth_information, Hash
attribute :student_expected_earnings_next_year, Hash
attribute :student_information, Hash
def initialize(proc_id, vnp_participant_id, student = nil) # rubocop:disable Lint/MissingSuper
@proc_id = proc_id
@vnp_participant_id = vnp_participant_id
@student = student
assign_attributes(student)
end
# rubocop:disable Metrics/MethodLength
def params_for_686c
{
vnp_proc_id: @proc_id,
vnp_ptcpnt_id: @vnp_participant_id,
saving_amt: student_networth_information&.dig('savings'),
real_estate_amt: student_networth_information&.dig('real_estate'),
other_asset_amt: student_networth_information&.dig('other_assets'),
rmks: @student&.dig('remarks'),
marage_dt: format_date(@student&.dig('marriage_date')),
agency_paying_tuitn_nm: nil,
stock_bond_amt: student_networth_information&.dig('securities'),
govt_paid_tuitn_ind: convert_boolean(@student&.dig('tuition_is_paid_by_gov_agency')),
govt_paid_tuitn_start_dt: format_date(@student&.dig('benefit_payment_date')),
term_year_emplmt_income_amt: student_earnings_from_school_year&.dig('earnings_from_all_employment'),
term_year_other_income_amt: student_earnings_from_school_year&.dig('all_other_income'),
term_year_ssa_income_amt: student_earnings_from_school_year&.dig('annual_social_security_payments'),
term_year_annty_income_amt: student_earnings_from_school_year&.dig('other_annuities_income'),
next_year_annty_income_amt: student_expected_earnings_next_year&.dig('other_annuities_income'),
next_year_emplmt_income_amt: student_expected_earnings_next_year&.dig('earnings_from_all_employment'),
next_year_other_income_amt: student_expected_earnings_next_year&.dig('all_other_income'),
next_year_ssa_income_amt: student_expected_earnings_next_year&.dig('annual_social_security_payments'),
acrdtdSchoolInd: convert_boolean(@student&.dig('school_information', 'is_school_accredited')),
atndedSchoolCntnusInd: convert_boolean(@student&.dig('school_information', 'student_is_enrolled_full_time')),
stopedAtndngSchoolDt: nil
}
end
# rubocop:enable Metrics/MethodLength
private
def convert_boolean(bool)
bool == true ? 'Y' : 'N'
end
def assign_attributes(data)
@student_address_marriage_tuition = data['student_address_marriage_tuition']
@student_earnings_from_school_year = data['student_earnings_from_school_year']
@student_networth_information = data['student_networth_information']
@student_expected_earnings_next_year = data['student_expected_earnings_next_year']
@student_information = data['student_information']
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/persistent_attachments/military_records.rb
|
# frozen_string_literal: true
class PersistentAttachments::MilitaryRecords < PersistentAttachment
include ::ClaimDocumentation::Uploader::Attachment.new(:file)
before_destroy(:delete_file)
def warnings
@warnings ||= []
end
private
def delete_file
file.delete
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/persistent_attachments/lgy_claim.rb
|
# frozen_string_literal: true
class PersistentAttachments::LgyClaim < PersistentAttachment
include ::ClaimDocumentation::Uploader::Attachment.new(:file)
before_destroy(:delete_file)
private
def delete_file
file.delete
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/persistent_attachments/dependency_claim.rb
|
# frozen_string_literal: true
class PersistentAttachments::DependencyClaim < PersistentAttachment
include ::ClaimDocumentation::Uploader::Attachment.new(:file)
before_destroy(:delete_file)
# @see PersistentAttachment#requires_stamped_pdf_validation
def requires_stamped_pdf_validation?
true
end
private
def delete_file
file.delete
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/persistent_attachments/va_form.rb
|
# frozen_string_literal: true
class PersistentAttachments::VAForm < PersistentAttachment
include ::FormUpload::Uploader::Attachment.new(:file)
before_destroy(:delete_file)
CONFIGS = Hash.new(
{ max_pages: 10, min_pages: 1 }
).merge(
{
'21-0779' => { max_pages: 4, min_pages: 2 },
'21-4192' => { max_pages: 2, min_pages: 2 },
'21-509' => { max_pages: 4, min_pages: 2 },
'21-526EZ' => { max_pages: 15, min_pages: 6 },
'21-686c' => { max_pages: 16, min_pages: 2 },
'21-8940' => { max_pages: 4, min_pages: 2 },
'21P-0516-1' => { max_pages: 2, min_pages: 2 },
'21P-0517-1' => { max_pages: 2, min_pages: 2 },
'21P-0518-1' => { max_pages: 2, min_pages: 2 },
'21P-0519C-1' => { max_pages: 2, min_pages: 2 },
'21P-0519S-1' => { max_pages: 2, min_pages: 2 },
'21P-530a' => { max_pages: 2, min_pages: 2 },
'21P-8049' => { max_pages: 4, min_pages: 4 },
'21-8951-2' => { max_pages: 3, min_pages: 2 },
'21-674b' => { max_pages: 2, min_pages: 2 },
'21-2680' => { max_pages: 4, min_pages: 4 },
'21-0788' => { max_pages: 2, min_pages: 2 },
'21-4193' => { max_pages: 3, min_pages: 2 },
'21P-4718a' => { max_pages: 2, min_pages: 2 },
'21-4140' => { max_pages: 2, min_pages: 2 },
'21P-4706c' => { max_pages: 4, min_pages: 4 },
'21-8960' => { max_pages: 2, min_pages: 2 },
'21-0304' => { max_pages: 4, min_pages: 3 },
'21-651' => { max_pages: 1, min_pages: 1 },
'21P-4185' => { max_pages: 2, min_pages: 2 }
}
)
def max_pages
CONFIGS[form_id][:max_pages]
end
def min_pages
CONFIGS[form_id][:min_pages]
end
def warnings
@warnings ||= []
end
def as_json(options = {})
super(options).merge(warnings:)
end
private
def delete_file
file.delete
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/persistent_attachments/claim_evidence.rb
|
# frozen_string_literal: true
# This class represents the generic and default persistent attachment type
# used by ClaimDocumentsController when a more specific subclass is not selected
# based on form_id. It provides the default override for claim evidence uploads.
#
# See ClaimDocumentsController#klass for how this class is selected.
class PersistentAttachments::ClaimEvidence < PersistentAttachment
# Leverages the Shrine gem library to provide file attachment functionality for this model.
include ::ClaimDocumentation::Uploader::Attachment.new(:file)
before_destroy(:delete_file)
# @see PersistentAttachment#requires_stamped_pdf_validation
def requires_stamped_pdf_validation?
true
end
private
# Deletes the associated file from storage.
#
# @return [void]
def delete_file
file.delete
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/persistent_attachments/va_form_documentation.rb
|
# frozen_string_literal: true
class PersistentAttachments::VAFormDocumentation < PersistentAttachment
include ::ClaimDocumentation::Uploader::Attachment.new(:file)
before_destroy(:delete_file)
private
def delete_file
file.delete
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/persistent_attachments/pension_burial.rb
|
# frozen_string_literal: true
class PersistentAttachments::PensionBurial < PersistentAttachment
include ::ClaimDocumentation::Uploader::Attachment.new(:file)
before_destroy(:delete_file)
private
def delete_file
file.delete
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/code_container.rb
|
# frozen_string_literal: true
module SignIn
class CodeContainer < Common::RedisStore
redis_store REDIS_CONFIG[:sign_in_code_container][:namespace]
redis_ttl REDIS_CONFIG[:sign_in_code_container][:each_ttl]
redis_key :code
attribute :code_challenge, String
attribute :code, String
attribute :client_id, String
attribute :user_verification_id, Integer
attribute :credential_email, String
attribute :user_attributes, Hash
attribute :device_sso, Boolean
attribute :web_sso_session_id, Integer
validates(:code, :user_verification_id, presence: true)
validate :confirm_client_id
private
def confirm_client_id
errors.add(:base, 'Client id must map to a configuration') unless ClientConfig.valid_client_id?(client_id:)
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/config_certificate.rb
|
# frozen_string_literal: true
module SignIn
class ConfigCertificate < ApplicationRecord
self.table_name = 'sign_in_config_certificates'
belongs_to :config, polymorphic: true
belongs_to :cert, class_name: 'SignIn::Certificate', foreign_key: :certificate_id, inverse_of: :config_certificates
accepts_nested_attributes_for :cert
validates_associated :cert
def cert_attributes=(attrs)
attrs = attrs.to_h.symbolize_keys
pem = attrs[:pem]
if pem.present?
existing_cert = SignIn::Certificate.find_by(pem:)
if existing_cert
self.cert = existing_cert
return
end
end
super
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/credential_level.rb
|
# frozen_string_literal: true
module SignIn
class CredentialLevel
include ActiveModel::Validations
attr_reader(
:requested_acr,
:current_ial,
:max_ial,
:credential_type,
:auto_uplevel
)
validates(:requested_acr, inclusion: { in: Constants::Auth::ACR_VALUES })
validates(:credential_type, inclusion: { in: Constants::Auth::CSP_TYPES })
validates(:current_ial, inclusion: { in: [Constants::Auth::IAL_ONE, Constants::Auth::IAL_TWO] })
validates(:max_ial, inclusion: { in: [Constants::Auth::IAL_ONE, Constants::Auth::IAL_TWO] })
validate(:max_ial_greater_than_or_equal_to_current_ial)
def initialize(requested_acr:, credential_type:, current_ial:, max_ial:, auto_uplevel: false)
@requested_acr = requested_acr
@credential_type = credential_type
@current_ial = current_ial
@max_ial = max_ial
@auto_uplevel = auto_uplevel
validate!
end
def can_uplevel_credential?
requested_acr == Constants::Auth::MIN && current_ial < max_ial
end
private
def persisted?
false
end
def max_ial_greater_than_or_equal_to_current_ial
errors.add(:max_ial, 'cannot be less than Current ial') if max_ial.to_i < current_ial.to_i
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/o_auth_session.rb
|
# frozen_string_literal: true
module SignIn
class OAuthSession < ApplicationRecord
belongs_to :user_account, dependent: nil
belongs_to :user_verification, dependent: nil
has_kms_key
has_encrypted :user_attributes, key: :kms_key, **lockbox_options
validates :handle, uniqueness: true, presence: true
validates :hashed_refresh_token, uniqueness: true, presence: true
validates :refresh_expiration, presence: true
validates :refresh_creation, presence: true
validate :confirm_client_id
def active?
refresh_valid? && session_max_valid?
end
def user_attributes_hash
@user_attributes_hash ||= user_attributes.present? ? JSON.parse(user_attributes) : {}
end
private
def refresh_valid?
Time.zone.now < refresh_expiration
end
def session_max_valid?
Time.zone.now < refresh_creation + Constants::RefreshToken::SESSION_MAX_VALIDITY_LENGTH_DAYS
end
def confirm_client_id
errors.add(:base, 'Client id must map to a configuration') unless ClientConfig.valid_client_id?(client_id:)
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/user_info.rb
|
# frozen_string_literal: true
module SignIn
class UserInfo
include ActiveModel::Model
include ActiveModel::Attributes
include ActiveModel::Serialization
GCID_TYPE_CODES = {
icn: '200M',
sec_id: '200PROV',
edipi: '200DOD',
mhv_ien: '200MHV',
npi_id: '200ENPI',
vhic_id: '200VHIC',
nwhin_id: '200NWS',
cerner_id: '200CRNR',
corp_id: '200CORP',
birls_id: '200BRLS',
salesforce_id: '200DSLF',
usaccess_piv: '200PUSA',
piv_id: '200PIV',
va_active_directory_id: '200AD',
usa_staff_id: '200USAF'
}.freeze
ALLOWED_GCID_CODES = GCID_TYPE_CODES.values.index_with(&:itself).freeze
NUMERIC_GCID_CODE = /\A\d+\z/
attribute :sub, :string
attribute :csp_type, :string
attribute :ial, :string
attribute :aal, :string
attribute :csp_uuid, :string
attribute :email, :string
attribute :full_name, :string
attribute :birth_date, :string
attribute :ssn, :string
attribute :gender, :string
attribute :address_street1, :string
attribute :address_street2, :string
attribute :address_city, :string
attribute :address_state, :string
attribute :address_country, :string
attribute :address_postal_code, :string
attribute :phone_number, :string
attribute :person_types, :string
attribute :icn, :string
attribute :sec_id, :string
attribute :edipi, :string
attribute :mhv_ien, :string
attribute :npi_id, :string
attribute :cerner_id, :string
attribute :corp_id, :string
attribute :birls, :string
attribute :gcids, :string
validate :gcids_have_approved_identifier
private
def gcids_have_approved_identifier
value = gcids
return if value.blank?
segments = value.split('|')
invalid = segments.reject do |segment|
next false if segment.blank?
code = segment.to_s.split('^', 4)[2]
next false if code.blank?
ALLOWED_GCID_CODES.key?(code) || code.match?(NUMERIC_GCID_CODE)
end
return if invalid.empty?
errors.add(:gcids, 'contains non-approved gcids')
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/state_code.rb
|
# frozen_string_literal: true
module SignIn
class StateCode < Common::RedisStore
redis_store REDIS_CONFIG[:sign_in_state_code][:namespace]
redis_ttl REDIS_CONFIG[:sign_in_state_code][:each_ttl]
redis_key :code
attribute :code, String
validates(:code, presence: true)
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/client_config.rb
|
# frozen_string_literal: true
module SignIn
class ClientConfig < ApplicationRecord
attribute :access_token_duration, :interval
attribute :refresh_token_duration, :interval
has_many :config_certificates, as: :config, dependent: :destroy, inverse_of: :config, index_errors: true
has_many :certs, through: :config_certificates, source: :cert, index_errors: true
accepts_nested_attributes_for :config_certificates, allow_destroy: true
validates :anti_csrf, inclusion: [true, false]
validates :redirect_uri, presence: true
validates :access_token_duration,
presence: true,
inclusion: { in: Constants::AccessToken::VALIDITY_LENGTHS, allow_nil: false }
validates :refresh_token_duration,
presence: true,
inclusion: { in: Constants::RefreshToken::VALIDITY_LENGTHS, allow_nil: false }
validates :authentication,
presence: true,
inclusion: { in: Constants::Auth::AUTHENTICATION_TYPES, allow_nil: false }
validates :shared_sessions, inclusion: [true, false]
validates :enforced_terms, inclusion: { in: Constants::Auth::ENFORCED_TERMS, allow_nil: true }
validates :terms_of_use_url, presence: true, if: :enforced_terms
validates :client_id, presence: true, uniqueness: true
validates :logout_redirect_uri, presence: true, if: :cookie_auth?
validates :access_token_attributes, inclusion: { in: Constants::AccessToken::USER_ATTRIBUTES }
validates :service_levels, presence: true, inclusion: { in: Constants::Auth::ACR_VALUES, allow_nil: false }
validates :credential_service_providers, presence: true,
inclusion: { in: Constants::Auth::CSP_TYPES, allow_nil: false }
validates :json_api_compatibility, inclusion: [true, false]
def self.valid_client_id?(client_id:)
find_by(client_id:).present?
end
def cookie_auth?
authentication == Constants::Auth::COOKIE
end
def api_auth?
authentication == Constants::Auth::API
end
def mock_auth?
authentication == Constants::Auth::MOCK && appropriate_mock_environment?
end
def va_terms_enforced?
enforced_terms == Constants::Auth::VA_TERMS
end
def valid_credential_service_provider?(type)
credential_service_providers.include?(type)
end
def valid_service_level?(acr)
service_levels.include?(acr)
end
def api_sso_enabled?
api_auth? && shared_sessions
end
def web_sso_enabled?
cookie_auth? && shared_sessions
end
def certs_attributes=(attributes)
normalized_attributes = attributes.is_a?(Hash) ? attributes.values : Array(attributes)
self.config_certificates_attributes = normalized_attributes.map do |cert_attrs|
cert_attrs = cert_attrs.to_h.symbolize_keys
should_destroy = ActiveModel::Type::Boolean.new.cast(cert_attrs[:_destroy])
if should_destroy
config_cert_id = find_config_certificate_for_destruction(cert_attrs)
{ id: config_cert_id, _destroy: true }.compact
else
cert = SignIn::Certificate.where(id: cert_attrs[:id].presence)
.or(SignIn::Certificate.where(pem: cert_attrs[:pem].presence))
.first
next if certs.include?(cert)
{ cert_attributes: { id: cert&.id, pem: cert_attrs[:pem].to_s }.compact }
end
end
end
def find_config_certificate_for_destruction(cert_attrs)
certificate_id = cert_attrs[:id].presence
return config_certificates.where(certificate_id:).pick(:id) if certificate_id
pem = cert_attrs[:pem].to_s.strip
return if pem.blank?
config_certificates.joins(:cert).where(sign_in_certificates: { pem: }).pick(:id)
end
def as_json(options = {})
super(options).tap do |hash|
hash['certs'] = certs.map(&:as_json)
end
end
private
def appropriate_mock_environment?
%w[test localhost development].include?(Settings.vsp_environment)
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/refresh_token.rb
|
# frozen_string_literal: true
module SignIn
class RefreshToken
include ActiveModel::Validations
attr_reader :user_uuid, :uuid, :session_handle, :parent_refresh_token_hash, :anti_csrf_token, :nonce, :version
validates :user_uuid, :uuid, :session_handle, :anti_csrf_token, :nonce, :version, presence: true
validates :version, inclusion: Constants::RefreshToken::VERSION_LIST
# rubocop:disable Metrics/ParameterLists
def initialize(session_handle:,
user_uuid:,
anti_csrf_token:,
uuid: create_uuid,
parent_refresh_token_hash: nil,
nonce: create_nonce,
version: Constants::RefreshToken::CURRENT_VERSION)
@user_uuid = user_uuid
@uuid = uuid
@session_handle = session_handle
@parent_refresh_token_hash = parent_refresh_token_hash
@anti_csrf_token = anti_csrf_token
@nonce = nonce
@version = version
validate!
end
# rubocop:enable Metrics/ParameterLists
def persisted?
false
end
def to_s
{
uuid:,
user_uuid:,
session_handle:,
version:
}
end
private
def create_uuid
SecureRandom.uuid
end
def create_nonce
SecureRandom.hex
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/user_code_map.rb
|
# frozen_string_literal: true
module SignIn
class UserCodeMap
include ActiveModel::Validations
attr_reader(
:login_code,
:type,
:client_state,
:client_config,
:terms_code
)
validates(:login_code, :type, :client_config, presence: true)
def initialize(login_code:,
type:,
client_config:,
client_state:,
terms_code:)
@login_code = login_code
@type = type
@client_config = client_config
@client_state = client_state
@terms_code = terms_code
validate!
end
def persisted?
false
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/state_payload.rb
|
# frozen_string_literal: true
module SignIn
class StatePayload
include ActiveModel::Validations
attr_reader(
:acr,
:client_id,
:type,
:code_challenge,
:client_state,
:code,
:scope,
:created_at
)
validates :code, :created_at, presence: true
validates :acr, inclusion: Constants::Auth::ACR_VALUES
validates :type, inclusion: Constants::Auth::CSP_TYPES
validates :client_state, length: { minimum: Constants::Auth::CLIENT_STATE_MINIMUM_LENGTH }, allow_blank: true
validate :confirm_client_id
# rubocop:disable Metrics/ParameterLists
def initialize(acr:,
client_id:,
type:,
code:,
scope: nil,
code_challenge: nil,
client_state: nil,
created_at: nil)
@acr = acr
@client_id = client_id
@type = type
@code_challenge = code_challenge
@client_state = client_state
@code = code
@scope = scope
@created_at = created_at || Time.zone.now.to_i
validate!
end
# rubocop:enable Metrics/ParameterLists
def persisted?
false
end
private
def confirm_client_id
errors.add(:base, 'Client id must map to a configuration') unless ClientConfig.valid_client_id?(client_id:)
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/terms_code_container.rb
|
# frozen_string_literal: true
module SignIn
class TermsCodeContainer < Common::RedisStore
redis_store REDIS_CONFIG[:sign_in_terms_code_container][:namespace]
redis_ttl REDIS_CONFIG[:sign_in_terms_code_container][:each_ttl]
redis_key :code
attribute :code, String
attribute :user_account_uuid, String
validates(:code, :user_account_uuid, presence: true)
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/validated_credential.rb
|
# frozen_string_literal: true
module SignIn
class ValidatedCredential
include ActiveModel::Validations
attr_reader(
:user_verification,
:credential_email,
:client_config,
:user_attributes,
:device_sso,
:web_sso_session_id
)
validates(
:user_verification,
:client_config,
presence: true
)
def initialize(user_verification:, # rubocop:disable Metrics/ParameterLists
client_config:,
credential_email:,
user_attributes:,
device_sso:,
web_sso_session_id:)
@user_verification = user_verification
@client_config = client_config
@credential_email = credential_email
@user_attributes = user_attributes
@device_sso = device_sso
@web_sso_session_id = web_sso_session_id
validate!
end
def persisted?
false
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/service_account_config.rb
|
# frozen_string_literal: true
module SignIn
class ServiceAccountConfig < ApplicationRecord
attribute :access_token_duration, :interval
has_many :config_certificates, as: :config, dependent: :destroy, inverse_of: :config, index_errors: true
has_many :certs, through: :config_certificates, source: :cert, index_errors: true
accepts_nested_attributes_for :config_certificates, allow_destroy: true
validates :service_account_id, presence: true, uniqueness: true
validates :description, presence: true
validates :access_token_audience, presence: true
validates :access_token_duration,
presence: true,
inclusion: { in: Constants::ServiceAccountAccessToken::VALIDITY_LENGTHS, allow_nil: false }
validates :access_token_user_attributes, inclusion: { in: Constants::ServiceAccountAccessToken::USER_ATTRIBUTES }
def certs_attributes=(attributes)
normalized_attributes = attributes.is_a?(Hash) ? attributes.values : Array(attributes)
self.config_certificates_attributes = normalized_attributes.map do |cert_attrs|
cert_attrs = cert_attrs.to_h.symbolize_keys
should_destroy = ActiveModel::Type::Boolean.new.cast(cert_attrs[:_destroy])
if should_destroy
config_cert_id = find_config_certificate_for_destruction(cert_attrs)
{ id: config_cert_id, _destroy: true }.compact
else
cert = SignIn::Certificate.where(id: cert_attrs[:id].presence)
.or(SignIn::Certificate.where(pem: cert_attrs[:pem].presence))
.first
next if certs.include?(cert)
{ cert_attributes: { id: cert&.id, pem: cert_attrs[:pem].to_s }.compact }
end
end
end
def find_config_certificate_for_destruction(cert_attrs)
certificate_id = cert_attrs[:id].presence
return config_certificates.where(certificate_id:).pick(:id) if certificate_id
pem = cert_attrs[:pem].to_s.strip
return if pem.blank?
config_certificates.joins(:cert).where(sign_in_certificates: { pem: }).pick(:id)
end
def as_json(options = {})
super(options).tap do |hash|
hash['certs'] = certs.map(&:as_json)
end
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/certificate.rb
|
# frozen_string_literal: true
module SignIn
class Certificate < ApplicationRecord
self.table_name = 'sign_in_certificates'
EXPIRING_WINDOW = 60.days
has_many :config_certificates, dependent: :destroy
has_many :client_configs, through: :config_certificates, source: :config, source_type: 'ClientConfig'
has_many :service_account_configs, through: :config_certificates, source: :config,
source_type: 'ServiceAccountConfig'
delegate :not_before, :not_after, :subject, :issuer, :serial, to: :x509
scope :active, -> { select(&:active?) }
scope :expired, -> { select(&:expired?) }
scope :expiring_soon, -> { select(&:expiring_soon?) }
scope :expiring_later, -> { select(&:expiring_later?) }
normalizes :pem, with: ->(value) { value.present? ? "#{value.chomp}\n" : value }
validates :pem, presence: true
validate :validate_x509
def x509
@x509 ||= OpenSSL::X509::Certificate.new(pem.to_s)
rescue OpenSSL::X509::CertificateError
nil
end
def x509?
x509.present?
end
def public_key
x509&.public_key
end
def expired?
x509? && not_after < Time.current
end
def expiring_soon?
x509? && !expired? && not_after <= EXPIRING_WINDOW.from_now
end
def expiring_later?
x509? && not_after > EXPIRING_WINDOW.from_now
end
def active?
x509? && not_after > Time.current
end
def status
if expired?
'expired'
elsif expiring_soon?
'expiring_soon'
elsif active?
'active'
end
end
private
def validate_x509
unless x509
errors.add(:pem, 'not a valid X.509 certificate')
return
end
errors.add(:pem, 'X.509 certificate is expired') if expired?
errors.add(:pem, 'X.509 certificate is not yet valid') if not_before > Time.current
errors.add(:pem, 'X.509 certificate is self-signed') if issuer == subject
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/service_account_access_token.rb
|
# frozen_string_literal: true
module SignIn
class ServiceAccountAccessToken
include ActiveModel::Validations
attr_reader(
:uuid,
:service_account_id,
:audience,
:scopes,
:user_attributes,
:user_identifier,
:version,
:expiration_time,
:created_time
)
validates(
:uuid,
:service_account_id,
:audience,
:user_identifier,
:version,
:expiration_time,
:created_time,
presence: true
)
validates :version, inclusion: Constants::ServiceAccountAccessToken::VERSION_LIST
# rubocop:disable Metrics/ParameterLists
def initialize(service_account_id:,
audience:,
user_identifier:,
scopes: [],
user_attributes: {},
uuid: nil,
version: nil,
expiration_time: nil,
created_time: nil)
@uuid = uuid || create_uuid
@service_account_id = service_account_id
@user_attributes = user_attributes
@user_identifier = user_identifier
@scopes = scopes
@audience = audience
@version = version || Constants::ServiceAccountAccessToken::CURRENT_VERSION
@expiration_time = expiration_time || set_expiration_time
@created_time = created_time || set_created_time
validate!
end
# rubocop:enable Metrics/ParameterLists
def persisted?
false
end
def to_s
{
uuid:,
service_account_id:,
user_attributes:,
user_identifier:,
scopes:,
audience:,
version:,
created_time: created_time.to_i,
expiration_time: expiration_time.to_i
}
end
private
def create_uuid
SecureRandom.uuid
end
def set_expiration_time
Time.zone.now + validity_length
end
def set_created_time
Time.zone.now
end
def validity_length
service_account_config.access_token_duration
end
def service_account_config
@service_account_config ||= ServiceAccountConfig.find_by(service_account_id:)
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/session_container.rb
|
# frozen_string_literal: true
module SignIn
class SessionContainer
include ActiveModel::Validations
attr_reader(
:session,
:refresh_token,
:access_token,
:anti_csrf_token,
:client_config,
:device_secret,
:web_sso_client
)
validates(
:session,
:refresh_token,
:access_token,
:anti_csrf_token,
:client_config,
presence: true
)
def initialize(session:, # rubocop:disable Metrics/ParameterLists
refresh_token:,
access_token:,
anti_csrf_token:,
client_config:,
device_secret: nil,
web_sso_client: false)
@session = session
@refresh_token = refresh_token
@access_token = access_token
@anti_csrf_token = anti_csrf_token
@client_config = client_config
@device_secret = device_secret
@web_sso_client = web_sso_client
validate!
end
def persisted?
false
end
def context
{
user_uuid: access_token.to_s[:user_uuid],
session_handle: session.handle,
client_id: session.client_id,
type: session.user_verification.credential_type,
icn: session.user_account.icn
}
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/sign_in/access_token.rb
|
# frozen_string_literal: true
module SignIn
class AccessToken
include ActiveModel::Validations
attr_reader(
:uuid,
:session_handle,
:client_id,
:user_uuid,
:audience,
:refresh_token_hash,
:anti_csrf_token,
:last_regeneration_time,
:parent_refresh_token_hash,
:version,
:expiration_time,
:created_time,
:user_attributes,
:device_secret_hash
)
validates(
:uuid,
:session_handle,
:client_id,
:user_uuid,
:audience,
:refresh_token_hash,
:anti_csrf_token,
:last_regeneration_time,
:version,
:expiration_time,
:created_time,
presence: true
)
validates :version, inclusion: Constants::AccessToken::VERSION_LIST
# rubocop:disable Metrics/ParameterLists
def initialize(session_handle:,
client_id:,
user_uuid:,
audience:,
refresh_token_hash:,
anti_csrf_token:,
last_regeneration_time:,
uuid: nil,
parent_refresh_token_hash: nil,
version: nil,
expiration_time: nil,
created_time: nil,
user_attributes: nil,
device_secret_hash: nil)
@uuid = uuid || create_uuid
@session_handle = session_handle
@client_id = client_id
@user_uuid = user_uuid
@audience = audience
@refresh_token_hash = refresh_token_hash
@anti_csrf_token = anti_csrf_token
@last_regeneration_time = last_regeneration_time
@parent_refresh_token_hash = parent_refresh_token_hash
@version = version || Constants::AccessToken::CURRENT_VERSION
@expiration_time = expiration_time || set_expiration_time
@created_time = created_time || set_created_time
@user_attributes = filter_user_attributes(user_attributes:)
@device_secret_hash = device_secret_hash
validate!
end
# rubocop:enable Metrics/ParameterLists
def persisted?
false
end
def to_s
{
uuid:,
user_uuid:,
session_handle:,
client_id:,
audience:,
version:,
last_regeneration_time: last_regeneration_time.to_i,
created_time: created_time.to_i,
expiration_time: expiration_time.to_i
}
end
private
def create_uuid
SecureRandom.uuid
end
def set_expiration_time
Time.zone.now + validity_length
end
def set_created_time
Time.zone.now
end
def validity_length
client_config.access_token_duration
end
def filter_user_attributes(user_attributes:)
return nil unless user_attributes.presence
user_attributes.with_indifferent_access.select { |key| client_config&.access_token_attributes&.include?(key) }
end
def client_config
@client_config ||= ClientConfig.find_by(client_id:)
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/chatbot/code_container.rb
|
# frozen_string_literal: true
module Chatbot
class CodeContainer < Common::RedisStore
redis_store REDIS_CONFIG[:chatbot_code_container][:namespace]
redis_ttl REDIS_CONFIG[:chatbot_code_container][:each_ttl]
redis_key :code
attribute :icn, String
attribute :code, String
validates(:icn, :code, presence: true)
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs/submission.rb
|
# frozen_string_literal: true
class BGS::Submission < Submission
self.table_name = 'bgs_submissions'
include SubmissionEncryption
has_many :submission_attempts, class_name: 'BGS::SubmissionAttempt', dependent: :destroy,
foreign_key: :bgs_submission_id, inverse_of: :submission
belongs_to :saved_claim, optional: true
def latest_attempt
submission_attempts.order(created_at: :desc).first
end
def latest_pending_attempt
submission_attempts.where(status: 'pending').order(created_at: :desc).first
end
def non_failure_attempt
submission_attempts.where(status: %w[pending submitted]).first
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/bgs/submission_attempt.rb
|
# frozen_string_literal: true
class BGS::SubmissionAttempt < SubmissionAttempt
self.table_name = 'bgs_submission_attempts'
include SubmissionAttemptEncryption
belongs_to :submission, class_name: 'BGS::Submission', foreign_key: :bgs_submission_id,
inverse_of: :submission_attempts
has_one :saved_claim, through: :submission
enum :status, {
pending: 'pending',
submitted: 'submitted',
failure: 'failure'
}
scope :by_claim_group, lambda { |parent_claim_id|
joins(submission: { saved_claim: :child_of_groups })
.where(saved_claim_groups: { parent_claim_id: })
}
STATS_KEY = 'api.bgs.submission_attempt'
def fail!(error:)
update(error_message: error&.message)
failure!
log_hash = status_change_hash
log_hash[:message] = 'BGS Submission Attempt failed'
monitor.track_request(:error, log_hash[:message], STATS_KEY, **log_hash)
end
def pending!
update(status: :pending)
log_hash = status_change_hash
log_hash[:message] = 'BGS Submission Attempt is pending'
monitor.track_request(:info, log_hash[:message], STATS_KEY, **log_hash)
end
def success!
submitted!
log_hash = status_change_hash
log_hash[:message] = 'BGS Submission Attempt is submitted'
monitor.track_request(:info, log_hash[:message], STATS_KEY, **log_hash)
end
def claim_type_end_product
data = metadata.present? ? JSON.parse(metadata) : {}
data['claim_type_end_product']
end
def monitor
@monitor ||= Logging::Monitor.new('bgs_submission_attempt')
end
def status_change_hash
{
submission_id: submission.id,
claim_id: submission.saved_claim_id,
form_type: submission.form_id,
from_state: previous_changes[:status]&.first,
to_state: status
}
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/async_transaction/base.rb
|
# frozen_string_literal: true
require 'json_marshal/marshaller'
module AsyncTransaction
class Base < ApplicationRecord
self.table_name = 'async_transactions'
REQUESTED = 'requested'
COMPLETED = 'completed'
DELETE_COMPLETED_AFTER = 1.month
scope :stale, lambda {
where('created_at < ?', DELETE_COMPLETED_AFTER.ago).where(status: COMPLETED)
}
serialize :metadata, coder: JsonMarshal::Marshaller
has_kms_key
has_encrypted :metadata, key: :kms_key, **lockbox_options
before_save :serialize_metadata
belongs_to :user_account, dependent: nil, optional: true
def serialize_metadata
self.metadata = metadata.to_json unless metadata.is_a?(String)
end
def parsed_metadata
JSON.parse(metadata)
end
validates :id, uniqueness: true
validates :user_uuid, :source, :status, :transaction_id, presence: true
validates :transaction_id,
uniqueness: { scope: :source, message: 'Transaction ID must be unique within a source.' }
end
end
|
0
|
code_files/vets-api-private/app/models/async_transaction
|
code_files/vets-api-private/app/models/async_transaction/va_profile/base.rb
|
# frozen_string_literal: true
module AsyncTransaction
module VAProfile
class Base < AsyncTransaction::Base
FINAL_STATUSES = %w[
REJECTED
COMPLETED_SUCCESS
COMPLETED_NO_CHANGES_DETECTED
COMPLETED_FAILURE
].freeze
REQUESTED = 'requested'
COMPLETED = 'completed'
validates :source_id, presence: true, unless: :initialize_person?
# Get most recent requested transaction for a user
#
# @param user [User] The user associated with the transaction
# @return [AsyncTransaction::VAProfile::Base] A AsyncTransaction::VAProfile::Base record,
# be it Email, Address, etc.
#
def self.last_requested_for_user(user)
where(
status: Base::REQUESTED,
user_uuid: user.uuid
).order(
created_at: :desc
).limit(1)
end
# Creates an initial AsyncTransaction record for ongoing tracking
#
# @param user [User] The user associated with the transaction
# @param response [VAProfile::ContactInformation::V2::TransactionResponse] An instance of
# a VAProfile::ContactInformation::V2::TransactionResponse class, be it Email, Address, etc.
# @return [AsyncTransaction::VAProfile::Base] A AsyncTransaction::VAProfile::Base record,
# be it Email, Address, etc.
#
def self.start(user, response)
# vet360_id is no longer required for Contact Information API V2
source_id = user.vet360_id || user.uuid
create(
user_uuid: user.uuid,
user_account: user.user_account,
source_id:,
source: 'va_profile',
status: REQUESTED,
transaction_id: response.transaction.id,
transaction_status: response.transaction.status,
metadata: response.transaction.messages
)
end
# Updates the status and transaction_status with fresh API data
# @param user [User] the user whose tx data is being updated
# @param service [VAProfile::ContactInformation::V2::Service] an initialized VAProfile client
# @param tx_id [int] the transaction_id
# @return [AsyncTransaction::VAProfile::Base]
def self.refresh_transaction_status(user, service, tx_id = nil)
transaction_record = find_transaction!(user.uuid, tx_id)
return transaction_record if transaction_record.finished?
api_response = Base.fetch_transaction(transaction_record, service)
update_transaction_from_api(transaction_record, api_response)
end
# Requests a transaction from VAProfile for an app transaction
# @param user [User] the user whose tx data is being updated
# @param transaction_record [AsyncTransaction::VAProfile::Base] the tx record to be checked
# @param service [VAProfile::ContactInformation::V2::Service] an initialized VAProfile client
# @return [VAProfile::Models::Transaction]
def self.fetch_transaction(transaction_record, service)
case transaction_record
when AsyncTransaction::VAProfile::AddressTransaction
service.get_address_transaction_status(transaction_record.transaction_id)
when AsyncTransaction::VAProfile::EmailTransaction
service.get_email_transaction_status(transaction_record.transaction_id)
when AsyncTransaction::VAProfile::TelephoneTransaction
service.get_telephone_transaction_status(transaction_record.transaction_id)
when AsyncTransaction::VAProfile::InitializePersonTransaction
service.get_person_transaction_status(transaction_record.transaction_id)
else
# Unexpected transaction type means something went sideways
raise
end
end
# Finds a transaction by transaction_id for a user
# @param user_uuid [String] the user's UUID
# @param transaction_id [String] the transaction UUID
# @return [AddressTransaction, EmailTransaction, TelephoneTransaction]
def self.find_transaction!(user_uuid, transaction_id)
Base.find_by(user_uuid:, transaction_id:) ||
AsyncTransaction::VAProfile::Base.find_by!(user_uuid:, transaction_id:)
end
def self.update_transaction_from_api(transaction_record, api_response)
transaction_record.status = COMPLETED if FINAL_STATUSES.include? api_response.transaction.status
transaction_record.transaction_status = api_response.transaction.status
transaction_record.metadata = api_response.transaction.messages
transaction_record.save!
transaction_record
end
# Returns true or false if a transaction is "over"
# @return [Boolean] true if status is "over"
# @note this checks transaction_status status fields, which should be redundant
def finished?
FINAL_STATUSES.include?(transaction_status) || status == COMPLETED
end
# Wrapper for .refresh_transaction_status which finds any outstanding transactions
# for a user and refreshes them
# @param user [User] the user whose transactions we're checking
# @param service [VAProfile::ContactInformation::V2::Service] an initialized VAProfile client
# @return [Array] An array with any outstanding transactions refreshed. Empty if none.
def self.refresh_transaction_statuses(user, service)
last_ongoing_transactions_for_user(user).each_with_object([]) do |transaction, array|
array << refresh_transaction_status(
user,
service,
transaction.transaction_id
)
end
end
# Find the most recent address, email, or telelphone transactions for a user
# @praram user [User] the user whose transactions we're finding
# @return [Array] an array of any outstanding transactions
def self.last_ongoing_transactions_for_user(user)
ongoing_transactions = []
%w[
Address
Email
Telephone
Permission
].each do |transaction_type|
ongoing_transactions += "AsyncTransaction::VAProfile::#{transaction_type}Transaction"
.constantize
.last_requested_for_user(user)
end
ongoing_transactions
end
private
def initialize_person?
type&.constantize == AsyncTransaction::VAProfile::InitializePersonTransaction
end
end
end
end
|
0
|
code_files/vets-api-private/app/models/async_transaction
|
code_files/vets-api-private/app/models/async_transaction/va_profile/address_transaction.rb
|
# frozen_string_literal: true
module AsyncTransaction
module VAProfile
class AddressTransaction < AsyncTransaction::VAProfile::Base; end
end
end
|
0
|
code_files/vets-api-private/app/models/async_transaction
|
code_files/vets-api-private/app/models/async_transaction/va_profile/telephone_transaction.rb
|
# frozen_string_literal: true
module AsyncTransaction
module VAProfile
class TelephoneTransaction < AsyncTransaction::VAProfile::Base; end
end
end
|
0
|
code_files/vets-api-private/app/models/async_transaction
|
code_files/vets-api-private/app/models/async_transaction/va_profile/initialize_person_transaction.rb
|
# frozen_string_literal: true
module AsyncTransaction
module VAProfile
class InitializePersonTransaction < AsyncTransaction::VAProfile::Base; end
end
end
|
0
|
code_files/vets-api-private/app/models/async_transaction
|
code_files/vets-api-private/app/models/async_transaction/va_profile/permission_transaction.rb
|
# frozen_string_literal: true
module AsyncTransaction
module VAProfile
class PermissionTransaction < AsyncTransaction::VAProfile::Base; end
end
end
|
0
|
code_files/vets-api-private/app/models/async_transaction
|
code_files/vets-api-private/app/models/async_transaction/va_profile/email_transaction.rb
|
# frozen_string_literal: true
module AsyncTransaction
module VAProfile
class EmailTransaction < AsyncTransaction::VAProfile::Base; end
end
end
|
0
|
code_files/vets-api-private/app/models/veteran_enrollment_system
|
code_files/vets-api-private/app/models/veteran_enrollment_system/form1095_b/form1095_b.rb
|
# frozen_string_literal: true
require 'common/models/resource'
module VeteranEnrollmentSystem
module Form1095B
class Form1095B
include Vets::Model
attribute :first_name, String
attribute :middle_name, String
attribute :last_name, String
attribute :last_4_ssn, String
attribute :birth_date, Date
attribute :address, String
attribute :city, String
attribute :state, String
attribute :province, String
attribute :country, String
attribute :zip_code, String
attribute :foreign_zip, String
attribute :is_corrected, Bool, default: false
attribute :coverage_months, Array
attribute :tax_year, String
def txt_file
template_path = self.class.txt_template_path(tax_year)
unless File.exist?(template_path)
Rails.logger.error "1095-B template for year #{tax_year} does not exist."
raise Common::Exceptions::UnprocessableEntity.new(
detail: "1095-B for tax year #{tax_year} not supported", source: self.class.name
)
end
template_data = attributes.merge(txt_form_data)
File.open(template_path, 'r') do |template_file|
template_file.read % template_data.symbolize_keys
end
end
def pdf_file
template_path = self.class.pdf_template_path(tax_year)
unless File.exist?(template_path) && respond_to?("pdf_#{tax_year}_attributes", true)
Rails.logger.error "1095-B template for year #{tax_year} does not exist."
raise Common::Exceptions::UnprocessableEntity.new(
detail: "1095-B for tax year #{tax_year} not supported", source: self.class.name
)
end
pdftk = PdfForms.new(Settings.binaries.pdftk)
tmp_file = Tempfile.new("1095B-#{SecureRandom.hex}.pdf")
generate_pdf(pdftk, tmp_file, template_path)
end
class << self
# there is some overlap in the data provided by coveredIndividual and responsibleIndividual.
# in the VA enrollment system, they are always the same.
def parse(form_data)
prepared_data = {
first_name: form_data['data']['coveredIndividual']['name']['firstName'],
middle_name: form_data['data']['coveredIndividual']['name']['middleName'],
last_name: form_data['data']['coveredIndividual']['name']['lastName'],
last_4_ssn: form_data['data']['coveredIndividual']['ssn']&.last(4).presence,
birth_date: form_data['data']['coveredIndividual']['dateOfBirth'],
address: form_data['data']['responsibleIndividual']['address']['street1'],
city: form_data['data']['responsibleIndividual']['address']['city'],
state: form_data['data']['responsibleIndividual']['address']['stateOrProvince'],
province: form_data['data']['responsibleIndividual']['address']['stateOrProvince'],
country: form_data['data']['responsibleIndividual']['address']['country'],
zip_code: form_data['data']['responsibleIndividual']['address']['zipOrPostalCode'],
foreign_zip: form_data['data']['responsibleIndividual']['address']['zipOrPostalCode'],
is_corrected: false, # this will always be false at this time
coverage_months: coverage_months(form_data),
tax_year: form_data['data']['taxYear']
}
new(prepared_data)
end
def available_years(periods)
years = periods.each_with_object([]) do |period, array|
start_date = period['startDate'].to_date.year
# if no end date, the user is still enrolled
end_date = period['endDate']&.to_date&.year || Date.current.year
array << start_date
array << end_date
if (end_date - start_date) > 1
intervening_years = (start_date..end_date).to_a
array.concat(intervening_years)
end
end.uniq.sort
years.filter { |year| year.between?(*available_years_range) }
end
def available_years_range
current_tax_year = Date.current.year - 1
# using a range of years because more years of form data will be available in the future
[current_tax_year, current_tax_year]
end
def pdf_template_path(year)
"lib/veteran_enrollment_system/form1095_b/templates/pdfs/1095b-#{year}.pdf"
end
def txt_template_path(year)
"lib/veteran_enrollment_system/form1095_b/templates/txts/1095b-#{year}.txt"
end
private
def coverage_months(form_data)
months = form_data['data']['coveredIndividual']['monthsCovered']
coverage_months = Date::MONTHNAMES.compact.map { |month| months&.include?(month.upcase) ? month.upcase : false }
covered_all = form_data['data']['coveredIndividual']['coveredAll12Months']
[covered_all, *coverage_months]
end
end
private
def country_and_zip
"#{country} #{zip_code || foreign_zip}"
end
def middle_initial
middle_name ? middle_name[0] : ''
end
def birthdate_unless_ssn
last_4_ssn.present? ? '' : birth_date.strftime('%m/%d/%Y')
end
def full_name
[first_name, middle_name.presence, last_name].compact.join(' ')
end
def name_with_middle_initial
[first_name, middle_initial.presence, last_name].compact.join(' ')
end
def txt_form_data
text_data = {
birth_date_field: birthdate_unless_ssn,
state_or_province: state || province,
country_and_zip:,
full_name:,
name_with_middle_initial:,
corrected: is_corrected ? 'X' : '--'
}
coverage_months.each_with_index do |val, i|
field_name = "coverage_month_#{i}"
text_data[field_name.to_sym] = val ? 'X' : '--'
end
text_data
end
def generate_pdf(pdftk, tmp_file, template_path)
pdftk.fill_form(
template_path,
tmp_file,
pdf_data,
flatten: true
)
ret_pdf = tmp_file.read
tmp_file.close
tmp_file.unlink
ret_pdf
end
# rubocop:disable Metrics/MethodLength
def pdf_data
year_specific_attributes = send("pdf_#{tax_year}_attributes")
{
'topmostSubform[0].Page1[0].Pg1Header[0].cb_1[1]': is_corrected && 2,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_10[0]': 'C',
'topmostSubform[0].Page1[0].f1_18[0]': 'US Department of Veterans Affairs',
'topmostSubform[0].Page1[0].f1_19[0]': '74-1612229',
'topmostSubform[0].Page1[0].f1_20[0]': '877-222-8387',
'topmostSubform[0].Page1[0].f1_21[0]': 'P.O. BOX 149975',
'topmostSubform[0].Page1[0].f1_22[0]': 'Austin',
'topmostSubform[0].Page1[0].f1_23[0]': 'TX',
'topmostSubform[0].Page1[0].f1_24[0]': '78714-8957',
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].f1_25[0]': first_name,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].f1_26[0]': middle_initial,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].f1_27[0]': last_name,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].f1_28[0]': last_4_ssn || '',
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].f1_29[0]': birthdate_unless_ssn,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_01[0]': coverage_months[0] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_02[0]': coverage_months[1] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_03[0]': coverage_months[2] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_04[0]': coverage_months[3] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_05[0]': coverage_months[4] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_06[0]': coverage_months[5] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_07[0]': coverage_months[6] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_08[0]': coverage_months[7] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_09[0]': coverage_months[8] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_10[0]': coverage_months[9] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_11[0]': coverage_months[10] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_12[0]': coverage_months[11] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_13[0]': coverage_months[12] && 1
}.merge(year_specific_attributes)
end
# rubocop:enable Metrics/MethodLength
def pdf_2024_attributes
{
'topmostSubform[0].Page1[0].Part1Contents[0].Line1[0].f1_01[0]': first_name,
'topmostSubform[0].Page1[0].Part1Contents[0].Line1[0].f1_02[0]': middle_name,
'topmostSubform[0].Page1[0].Part1Contents[0].Line1[0].f1_03[0]': last_name,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_04[0]': last_4_ssn || '',
'topmostSubform[0].Page1[0].Part1Contents[0].f1_05[0]': birthdate_unless_ssn,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_06[0]': address,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_07[0]': city,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_08[0]': state || province,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_09[0]': country_and_zip
}
end
def pdf_2025_attributes
{
'topmostSubform[0].Page1[0].Part1Contents[0].Line1[0].f1_1[0]': first_name,
'topmostSubform[0].Page1[0].Part1Contents[0].Line1[0].f1_2[0]': middle_name,
'topmostSubform[0].Page1[0].Part1Contents[0].Line1[0].f1_3[0]': last_name,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_4[0]': last_4_ssn || '',
'topmostSubform[0].Page1[0].Part1Contents[0].f1_5[0]': birthdate_unless_ssn,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_6[0]': address,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_7[0]': city,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_8[0]': state || province,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_9[0]': country_and_zip
}
end
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/base.rb
|
# frozen_string_literal: true
require 'vets/model'
# Parent class for other Preneeds Burial form related models
# Should not be initialized directly
#
module Preneeds
class Base
include Vets::Model
# Override `as_json`
#
# @param options [Hash]
#
# @see ActiveModel::Serializers::JSON
#
def as_json(options = {})
super(options).deep_transform_keys { |key| key.camelize(:lower) }
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/claimant.rb
|
# frozen_string_literal: true
module Preneeds
# Models an Claimant from a {Preneeds::BurialForm} form
#
# @!attribute date_of_birth
# @return [String] claimant date of birth
# @!attribute desired_cemetery
# @return [String] cemetery number
# @!attribute email
# @return [String] claimant email
# @!attribute phone_number
# @return [String] claimant phone number
# @!attribute relationship_to_vet
# @return [String] code representing claimant's relationship to servicemember; one of '1', '2', '3', or '4'
# @!attribute ssn
# @return [String] claimant's social security number
# @!attribute name
# @return [Preneeds::FullName] claimant's full name
# @!attribute address
# @return [Preneeds::Address] claimant's address
#
class Claimant < Preneeds::Base
attribute :date_of_birth, String
attribute :desired_cemetery, String
attribute :email, String
attribute :phone_number, String
attribute :relationship_to_vet, String
attribute :ssn, String
attribute :name, Preneeds::FullName
attribute :address, Preneeds::Address
# (see Preneeds::BurialForm#as_eoas)
#
def as_eoas
hash = {
address: address&.as_eoas, dateOfBirth: date_of_birth, desiredCemetery: desired_cemetery,
email:, name: name&.as_eoas, phoneNumber: phone_number,
relationshipToVet: relationship_to_vet, ssn:
}
%i[email phoneNumber desiredCemetery].each { |key| hash.delete(key) if hash[key].blank? }
hash
end
# (see Preneeds::Applicant.permitted_params)
#
def self.permitted_params
[
:date_of_birth, :desired_cemetery, :email, :completing_reason, :phone_number, :relationship_to_vet, :ssn,
{ address: Preneeds::Address.permitted_params, name: Preneeds::FullName.permitted_params }
]
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/veteran.rb
|
# frozen_string_literal: true
module Preneeds
# Models a veteran from a {Preneeds::BurialForm} form
#
# @!attribute date_of_birth
# @return [String] veteran's date of birth
# @!attribute date_of_death
# @return [String] veteran's date of death
# @!attribute gender
# @return [String] veteran's gender
# @!attribute is_deceased
# @return [String] is veteran deceased? 'yes' or 'no'
# @!attribute marital_status
# @return [String] veteran's marital status
# @!attribute military_service_number
# @return [String] veteran's military service number
# @!attribute place_of_birth
# @return [String] veteran's place of birth
# @!attribute ssn
# @return [String] veteran's social security number
# @!attribute va_claim_number
# @return [String] veteran's VA claim number
# @!attribute military_status
# @return [String] veteran's military status
# @!attribute address
# @return [Preneeds::Address] veteran's address
# @!attribute current_name
# @return [Preneeds::FullName] veteran's current name
# @!attribute service_name
# @return [Preneeds::FullName] veteran's name when serving
# @!attribute service_records
# @return [Array<Preneeds::ServiceRecord>] veteran's service records
#
class Veteran < Preneeds::Base
attribute :date_of_birth, String
attribute :date_of_death, String
attribute :gender, String
attribute :is_deceased, String
attribute :marital_status, String
attribute :military_service_number, String
attribute :place_of_birth, String
attribute :ssn, String
attribute :va_claim_number, String
attribute :military_status, String
attribute :race, Preneeds::Race
attribute :address, Preneeds::Address
attribute :current_name, Preneeds::FullName
attribute :service_name, Preneeds::FullName
attribute :service_records, Preneeds::ServiceRecord, array: true
# (see Preneeds::BurialForm#as_eoas)
#
def as_eoas
hash = {
address: address&.as_eoas, currentName: current_name.as_eoas, dateOfBirth: date_of_birth,
dateOfDeath: date_of_death, gender:,
race: race&.as_eoas,
isDeceased: is_deceased,
maritalStatus: marital_status, militaryServiceNumber: military_service_number,
placeOfBirth: place_of_birth, serviceName: service_name.as_eoas,
serviceRecords: service_records.map(&:as_eoas), ssn:, vaClaimNumber: va_claim_number,
militaryStatus: military_status
}
%i[
dateOfBirth dateOfDeath vaClaimNumber placeOfBirth militaryServiceNumber
].each { |key| hash.delete(key) if hash[key].blank? }
hash
end
# (see Preneeds::Applicant.permitted_params)
#
def self.permitted_params
[
:date_of_birth, :date_of_death, :gender, :is_deceased, :marital_status,
:military_service_number, :place_of_birth, :ssn, :va_claim_number, :military_status,
{ race: Preneeds::Race.permitted_params,
address: Preneeds::Address.permitted_params,
current_name: Preneeds::FullName.permitted_params,
service_name: Preneeds::FullName.permitted_params,
service_records: [Preneeds::ServiceRecord.permitted_params] }
]
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/preneed_attachment.rb
|
# frozen_string_literal: true
module Preneeds
# Models the actual attachments uploaded for a {Preneeds::BurialForm} form
#
class PreneedAttachment < FormAttachment
# Set for parent class to use appropriate uploader
#
ATTACHMENT_UPLOADER_CLASS = PreneedAttachmentUploader
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/date_range.rb
|
# frozen_string_literal: true
module Preneeds
# Models a date range from a {Preneeds::BurialForm} form
#
# @!attribute from
# @return [String] 'from' date
# @!attribute to
# @return [String] 'to' date
#
class DateRange < Preneeds::Base
attribute :from, String
attribute :to, String
# (see Preneeds::Applicant.permitted_params)
#
def self.permitted_params
%i[from to]
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/attachment_type.rb
|
# frozen_string_literal: true
require 'vets/model'
module Preneeds
# Models an attachment type from the EOAS service.
# For use within the {Preneeds::BurialForm} form.
#
# @!attribute attachment_type_id
# @return [Integer] attachment type id
# @!attribute description
# @return [String] attachment type description
#
class AttachmentType
include Vets::Model
attribute :attachment_type_id, Integer
attribute :description, String
default_sort_by description: :asc
# Alias for :attachment_type_id attribute
#
# @return [Integer] attachment type id
#
def id
attachment_type_id
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/attachment.rb
|
# frozen_string_literal: true
module Preneeds
# Models a {Preneeds::BurialForm} form attachment
#
# @!attribute attachment_type
# @return [Preneeds::AttachmentType] {Preneeds::AttachmentType} object
# @!attribute sending_source
# @return [String] sending source; currently hard coded
# @!attribute file
# @return [CarrierWave::Storage::AWSFile, CarrierWave::SanitizedFile]
# @!attribute name
# @return [String] attachment name
# @!attribute data_handler
# @return [String] auto-generated attachment id
#
class Attachment < Preneeds::Base
# string to populate #sending_source
#
VETS_GOV = 'vets.gov'
attribute :attachment_type, Preneeds::AttachmentType
attribute :sending_source, String, default: VETS_GOV
attribute :file, (Rails.env.production? ? CarrierWave::Storage::AWSFile : CarrierWave::SanitizedFile)
attribute :name, String
attr_reader :data_handler
# Creates a new instance of {Preneeds::Attachment}
#
# @param args [Hash] hash with keys that correspond to attributes
#
def initialize(*args)
super
@data_handler = SecureRandom.hex
end
# (see Preneeds::BurialForm#as_eoas)
#
def as_eoas
{
attachmentType: {
attachmentTypeId: attachment_type.attachment_type_id
},
dataHandler: {
'inc:Include': '',
attributes!: {
'inc:Include': {
href: "cid:#{@data_handler}",
'xmlns:inc': 'http://www.w3.org/2004/08/xop/include'
}
}
},
description: name,
sendingName: VETS_GOV,
sendingSource: sending_source
}
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/preneed_attachment_hash.rb
|
# frozen_string_literal: true
module Preneeds
# Models a {Preneeds::BurialForm} form attachment.
# This is the data about the actual attachment, {Preneeds::Attachment}.
#
# @!attribute confirmation_code
# @return [String] guid of uploaded attachment
# @!attribute attachment_id
# @return [String] attachment id
# @!attribute name
# @return [String] attachment file name
#
class PreneedAttachmentHash < Preneeds::Base
attribute :confirmation_code, String
attribute :attachment_id, String
attribute :name, String
# (see Preneeds::Applicant.permitted_params)
#
def self.permitted_params
%i[confirmation_code attachment_id name]
end
# @return [CarrierWave::Storage::AWSFile, CarrierWave::SanitizedFile] the previously uploaded file
#
def get_file
::Preneeds::PreneedAttachment.find_by(guid: confirmation_code).get_file
end
# @return [Preneeds::Attachment] the {Preneeds::Attachment} documented by this objects attributes
#
def to_attachment
Preneeds::Attachment.new(
attachment_type: AttachmentType.new(
attachment_type_id: attachment_id
),
file: get_file,
name:
)
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/preneed_submission.rb
|
# frozen_string_literal: true
module Preneeds
# A record to track a {Preneeds::BurialForm} form submission.
#
# @!attribute id
# @return [Integer] auto-increment primary key.
# @!attribute tracking_number
# @return (see Preneeds::ReceiveApplication#tracking_number)
# @!attribute application_uuid
# @return (see Preneeds::ReceiveApplication#application_uuid)
# @!attribute return_description
# @return (see Preneeds::ReceiveApplication#return_description)
# @!attribute return_code
# @return (see Preneeds::ReceiveApplication#return_code)
# @!attribute created_at
# @return [Timestamp] created at date.
# @!attribute updated_at
# @return [Timestamp] updated at date.
#
class PreneedSubmission < ApplicationRecord
validates :tracking_number, :return_description, presence: true
validates :tracking_number, :application_uuid, uniqueness: true
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/race.rb
|
# frozen_string_literal: true
module Preneeds
class Race < Preneeds::Base
ATTRIBUTE_MAPPING = {
'I' => :is_american_indian_or_alaskan_native,
'A' => :is_asian,
'B' => :is_black_or_african_american,
'H' => :is_spanish_hispanic_latino,
'U' => :not_spanish_hispanic_latino,
'P' => :is_native_hawaiian_or_other_pacific_islander,
'W' => :is_white
}.freeze
ATTRIBUTE_MAPPING.each_value do |attr|
attribute(attr, Bool, default: false)
end
def as_eoas
return_val = []
ATTRIBUTE_MAPPING.each do |k, v|
if public_send(v)
return_val << {
raceCd: k
}
end
end
return_val
end
def self.permitted_params
ATTRIBUTE_MAPPING.values
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/cemetery.rb
|
# frozen_string_literal: true
require 'vets/model'
module Preneeds
# Models a cemetery from the EOAS service.
# For use within the {Preneeds::BurialForm} form.
#
# @!attribute cemetery_type
# @return [String] cemetery type; one of 'N', 'S', 'I', 'A', 'M'
# @!attribute name
# @return [String] name of cemetery
# @!attribute num
# @return [String] cemetery number
#
class Cemetery
include Vets::Model
attribute :cemetery_type, String
attribute :name, String
attribute :num, String
default_sort_by name: :asc
# Alias of #num
# @return [String] cemetery number
#
def id
num
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/full_name.rb
|
# frozen_string_literal: true
module Preneeds
# Models a full name for persons included in a {Preneeds::BurialForm} form
#
# @!attribute first
# @return [String] first name
# @!attribute last
# @return [String] last name
# @!attribute maiden
# @return [String] maiden name
# @!attribute middle
# @return [String] middle name
# @!attribute suffix
# @return [String] name suffix
#
class FullName < Preneeds::Base
attribute :first, String
attribute :last, String
attribute :maiden, String
attribute :middle, String
attribute :suffix, String
# (see Preneeds::BurialForm#as_eoas)
#
def as_eoas
hash = {
firstName: first, lastName: last, maidenName: maiden,
middleName: middle, suffix:
}
%i[maidenName middleName suffix].each { |key| hash.delete(key) if hash[key].blank? }
hash
end
# (see Preneeds::Applicant.permitted_params)
#
def self.permitted_params
%i[first last maiden middle suffix]
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/currently_buried_person.rb
|
# frozen_string_literal: true
module Preneeds
# Models a currently buried person under a veteran's benefit from a {Preneeds::BurialForm} form
#
# @!attribute cemetery_number
# @return [String] cemetery number
# @!attribute name
# @return [Preneeds::FullName] currently buried person's full name
#
class CurrentlyBuriedPerson < Preneeds::Base
attribute :cemetery_number, String
attribute :name, Preneeds::FullName
# (see Preneeds::BurialForm#as_eoas)
#
def as_eoas
{ cemeteryNumber: cemetery_number, name: name.as_eoas }
end
# (see Preneeds::Applicant.permitted_params)
#
def self.permitted_params
[:cemetery_number, { name: Preneeds::FullName.permitted_params }]
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/military_rank_input.rb
|
# frozen_string_literal: true
require 'vets/model'
module Preneeds
# Models the input needed to query {Preneeds::Service#get_military_rank_for_branch_of_service}
# For use within the {Preneeds::BurialForm} form.
#
# @!attribute branch_of_service
# @return [String] branch of service abbreviated code
# @!attribute start_date
# @return [XmlDate] start date for branch of service
# @!attribute end_date
# @return [XmlDate] end date of branch of service.
#
class MilitaryRankInput
include Vets::Model
# Some branches have no end_date, but api requires it just the same
validates :start_date, :end_date, presence: true, format: /\A\d{4}-\d{2}-\d{2}\z/
validates :branch_of_service, format: /\A\w{2}\z/
attribute :branch_of_service, String
attribute :start_date, Vets::Type::XmlDate
attribute :end_date, Vets::Type::XmlDate
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/receive_application.rb
|
# frozen_string_literal: true
require 'vets/model'
module Preneeds
# Objects used to model pertinent data about a submitted {Preneeds::BurialForm} form.
#
# @!attribute tracking_number
# @return (see Preneeds::BurialForm#tracking_number)
# @!attribute return_code
# @return [Integer] submission's return code - from EOAS
# @!attribute application_uuid
# @return [String] submitted application's uuid - from EOAS
# @!attribute return_description
# @return [String] submission's result - from EOAS
# @!attribute submitted_at
# @return [Time] current time
class ReceiveApplication
include Vets::Model
attribute :tracking_number, String
attribute :return_code, Integer
attribute :application_uuid, String
attribute :return_description, String
attribute :submitted_at, Time, default: :current_time
# Alias for #tracking_number
#
def receive_application_id
tracking_number
end
# @return [Time] current time
#
def current_time
Time.zone.now
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/service_record.rb
|
# frozen_string_literal: true
module Preneeds
# Models service record information for a {Preneeds::BurialForm} form
#
# @!attribute service_branch
# @return (see Preneeds::BranchesOfService#code)
# @!attribute discharge_type
# @return (see Preneeds::DischargeType#id)
# @!attribute highest_rank
# @return [String] highest rank achieved
# @!attribute national_guard_state
# @return [String] state - for national guard service only
# @!attribute date_range
# @return [Preneeds::DateRange] service date range
#
class ServiceRecord < Preneeds::Base
attribute :service_branch, String
attribute :discharge_type, String
attribute :highest_rank, String
attribute :national_guard_state, String
attribute :date_range, Preneeds::DateRange
# (see Preneeds::BurialForm#as_eoas)
#
def as_eoas
hash = {
branchOfService: service_branch, dischargeType: discharge_type,
enteredOnDutyDate: date_range.try(:from), highestRank: highest_rank,
nationalGuardState: national_guard_state, releaseFromDutyDate: date_range.try(:to)
}
%i[
enteredOnDutyDate releaseFromDutyDate highestRank nationalGuardState dischargeType
].each do |key|
hash.delete(key) if hash[key].blank?
end
hash
end
# (see Preneeds::Applicant.permitted_params)
#
def self.permitted_params
[
:service_branch, :discharge_type, :highest_rank, :national_guard_state,
{ date_range: Preneeds::DateRange.permitted_params }
]
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/address.rb
|
# frozen_string_literal: true
module Preneeds
# Models an address from a {Preneeds::BurialForm} form
#
# @!attribute street
# @return [String] address line 1
# @!attribute street2
# @return [String] address line 2
# @!attribute city
# @return [String] address city
# @!attribute country
# @return [String] address country
# @!attribute state
# @return [String] address state
# @!attribute postal_code
# @return [String] address postal code
#
class Address < Preneeds::Base
attribute :street, String
attribute :street2, String
attribute :city, String
attribute :country, String
attribute :state, String
attribute :postal_code, String
# (see Preneeds::BurialForm#as_eoas)
#
def as_eoas
hash = {
address1: street, address2: street2, city:,
countryCode: country, postalZip: postal_code, state: state || ''
}
hash.delete(:address2) if hash[:address2].blank?
hash
end
# (see Preneeds::Applicant.permitted_params)
#
def self.permitted_params
attribute_set.map { |a| a.name.to_sym }
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/applicant.rb
|
# frozen_string_literal: true
module Preneeds
# Models an Applicant from a {Preneeds::BurialForm} form
#
# @!attribute applicant_email
# @return [String] applicant's email
# @!attribute applicant_phone_number
# @return [String] applicant's phone number
# @!attribute applicant_relationship_to_claimant
# @return [String] applicant's relationship to claimant
# @!attribute completing_reason
# @return [String] completing reason. Currently hard coded.
# @!attribute mailing_address
# @return [Preneeds::Address] applicant's mailing address
# @!attribute name
# @return [Preneeds::FullName] applicant's name
#
class Applicant < Preneeds::Base
attribute :applicant_email, String
attribute :applicant_phone_number, String
attribute :applicant_relationship_to_claimant, String
attribute :completing_reason, String, default: 'vets.gov application'
attribute :mailing_address, Preneeds::Address
attribute :name, Preneeds::FullName
# (see Preneeds::BurialForm#as_eoas)
#
def as_eoas
{
applicantEmail: applicant_email, applicantPhoneNumber: applicant_phone_number,
applicantRelationshipToClaimant: applicant_relationship_to_claimant,
completingReason: completing_reason, mailingAddress: mailing_address&.as_eoas,
name: name&.as_eoas
}
end
# List of permitted params for use with Strong Parameters
#
# @return [Array] array of class attributes as symbols
#
def self.permitted_params
[
:applicant_email, :applicant_phone_number, :applicant_relationship_to_claimant, :completing_reason,
{ mailing_address: Preneeds::Address.permitted_params, name: Preneeds::FullName.permitted_params }
]
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/preneeds/burial_form.rb
|
# frozen_string_literal: true
require 'vets/model'
# Preneeds namespace
#
module Preneeds
# Models a Preneeds Burial form. This class (and associationed classes) is used to store form details and to
# generate the XML request for submission to the EOAS service
#
# @!attribute application_status
# @return [String] currently always blank
# @!attribute preneed_attachments
# @return [Array<PreneedAttachmentHash>] documents provided by the end user
# @!attribute has_currently_buried
# @return [String] '1' for Yes, '2' for No, '3' for Don't know
# @!attribute sending_application
# @return [String] hard coded as 'va.gov'
# @!attribute sending_code
# @return [String] currently always blank
# @!attribute sent_time
# @return [Time] current time
# @!attribute tracking_number
# @return [String] SecureRandom generated tracking number sent with submission to EOAS
# @!attribute applicant
# @return [Preneeds::Applicant] Applicant object. Applicant is person filling out the form.
# @!attribute claimant
# @return [Preneeds::Claimant] Claimant object. Claimant is the person applying for the
# benefit (veteran or relative)
# @!attribute currently_buried_persons
# @return [Array<Preneeds::CurrentlyBuriedPerson>] CurrentlyBuriedPerson objects representing individuals burried in
# VA national cemeteries under the sponsor's eligibility
# @!attribute veteran
# @return [Preneeds::Veteran] Veteran object. Veteran is the person who is the owner of the benefit.
#
class BurialForm < Preneeds::Base
include Vets::Model
# Preneeds Burial Form official form id
#
FORM = '40-10007'
attribute :application_status, String, default: ''
attribute :preneed_attachments, PreneedAttachmentHash, array: true
attribute :has_currently_buried, String
attribute :sending_application, String, default: 'vets.gov'
attribute :sending_code, String, default: ''
attribute :sent_time, Vets::Type::UTCTime, default: :current_time
attribute :tracking_number, String, default: :generate_tracking_number
attribute :applicant, Preneeds::Applicant
attribute :claimant, Preneeds::Claimant
attribute :currently_buried_persons, Preneeds::CurrentlyBuriedPerson, array: true
attribute :veteran, Preneeds::Veteran
# keeping this name because it matches the previous attribute
# @return [Bool]
#
def has_attachments
preneed_attachments.present?
end
# @return [Array<Preneeds::Attachment>] #preneed_attachments converted to Array of {Preneeds::Attachment}
def attachments
@attachments ||= preneed_attachments.map(&:to_attachment)
end
# @return [Time] current UTC time
#
def current_time
Time.now.utc
end
# @return [String] randomly generated tracking number
#
def generate_tracking_number
"#{SecureRandom.base64(14).tr('+/=', '0aZ')[0..-3]}VG"
end
# Converts object attributes to a hash to be used when constructing a SOAP request body.
# Hash attributes must correspond to XSD ordering or API call will fail
#
# @return [Hash] object attributes and association objects converted to EOAS service compatible hash
#
def as_eoas
hash = {
applicant: applicant&.as_eoas, applicationStatus: application_status,
attachments: attachments.map(&:as_eoas),
claimant: claimant&.as_eoas, currentlyBuriedPersons: currently_buried_persons.map(&:as_eoas),
hasAttachments: has_attachments, hasCurrentlyBuried: has_currently_buried,
sendingApplication: sending_application, sendingCode: sending_code || '', sentTime: sent_time.iso8601,
trackingNumber: tracking_number, veteran: veteran&.as_eoas
}
[:currentlyBuriedPersons].each do |key|
hash.delete(key) if hash[key].blank?
end
Common::HashHelpers.deep_compact(hash)
end
# @return [Array<String>] array of strings detailing schema validation failures. empty array if form is valid
#
def self.validate(schema, form, root = 'application')
JSON::Validator.fully_validate(schema, { root => form&.as_json }, validate_schema: true)
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/saved_claim/disability_compensation.rb
|
# frozen_string_literal: true
require 'evss/disability_compensation_form/data_translation_all_claim'
require 'evss/disability_compensation_form/form4142'
require 'evss/disability_compensation_form/form0781'
require 'evss/disability_compensation_form/form8940'
require 'bgs/disability_compensation_form_flashes'
class SavedClaim::DisabilityCompensation < SavedClaim
attr_accessor :form_hash
# For backwards compatibility, FORM constant needs to be set
# subclasses will overwrite this constant when using `add_form_and_validation`
const_set('FORM', '21-526EZ')
def self.from_hash(hash)
saved_claim = new(form: hash['form526'].to_json)
saved_claim.form_hash = hash
saved_claim
end
def to_submission_data(user)
form4142 = EVSS::DisabilityCompensationForm::Form4142.new(user, @form_hash.deep_dup).translate
form526 = @form_hash.deep_dup
dis_form = EVSS::DisabilityCompensationForm::DataTranslationAllClaim.new(user, form526, form4142.present?).translate
claimed_disabilities = dis_form.dig('form526', 'disabilities')
form526_uploads = form526['form526'].delete('attachments')
{
Form526Submission::FORM_526 => dis_form,
Form526Submission::FORM_526_UPLOADS => form526_uploads,
Form526Submission::FORM_4142 => form4142,
Form526Submission::FORM_0781 => EVSS::DisabilityCompensationForm::Form0781.new(user,
@form_hash.deep_dup).translate,
Form526Submission::FORM_8940 => EVSS::DisabilityCompensationForm::Form8940.new(user,
@form_hash.deep_dup).translate,
'flashes' => BGS::DisabilityCompensationFormFlashes.new(user, @form_hash.deep_dup, claimed_disabilities).translate
}.to_json
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/saved_claim/caregivers_assistance_claim.rb
|
# frozen_string_literal: true
require 'pdf_fill/filler'
class SavedClaim::CaregiversAssistanceClaim < SavedClaim
FORM = '10-10CG'
has_one :submission,
class_name: 'Form1010cg::Submission',
foreign_key: 'claim_guid',
primary_key: 'guid',
inverse_of: :claim,
dependent: :destroy
accepts_nested_attributes_for :submission
before_destroy(:destroy_attachment)
def process_attachments!
# Inherited from SavedClaim. Disabling since this claim does not require attachements.
raise NotImplementedError, 'Not Implemented for Form 10-10CG'
end
def to_pdf(filename = nil, **)
# We never save the claim, so we don't have an id to provide for the filename.
# Instead we'll create a filename with this format "10-10cg_{uuid}"
name = filename || guid
PdfFill::Filler.fill_form(self, name, **)
rescue => e
Rails.logger.error("Failed to generate PDF: #{e.message}")
PersonalInformationLog.create(data: { form: parsed_form, file_name: name },
error_class: '1010CGPdfGenerationError')
raise
end
# SavedClaims require regional_office to be defined, CaregiversAssistanceClaim has no purpose for it.
#
# CaregiversAssistanceClaims are not processed regional VA offices.
# The claim's form will contain a "Planned Clinic" (a VA facility that the end-user provided in the form).
# This facility is where the end-user's point of contact will be for post-submission processing.
def regional_office
[]
end
def form_subjects
if form.nil?
[]
else
parsed_form.keys.find_all do |k|
%w[veteran primaryCaregiver secondaryCaregiverOne secondaryCaregiverTwo].include?(k)
end
end
end
def veteran_data
parsed_form['veteran'] unless form.nil?
end
def primary_caregiver_data
parsed_form['primaryCaregiver'] unless form.nil?
end
def secondary_caregiver_one_data
parsed_form['secondaryCaregiverOne'] unless form.nil?
end
def secondary_caregiver_two_data
parsed_form['secondaryCaregiverTwo'] unless form.nil?
end
private
def destroy_attachment
return if form.blank?
Form1010cg::Attachment.find_by(guid: parsed_form['poaAttachmentId'])&.destroy!
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/saved_claim/coe_claim.rb
|
# frozen_string_literal: true
class SavedClaim::CoeClaim < SavedClaim
FORM = '26-1880'
def send_to_lgy(edipi:, icn:)
@edipi = edipi
@icn = icn
# If the EDIPI is blank, throw an error
if @edipi.blank?
Rails.logger.error('COE application cannot be submitted without an edipi!')
# Otherwise, submit the claim to the LGY API
else
Rails.logger.info('Begin COE claim submission to LGY API', guid:)
response = lgy_service.put_application(payload: prepare_form_data)
Rails.logger.info('COE claim submitted to LGY API', guid:)
process_attachments!
response['reference_number']
end
rescue Common::Client::Errors::ClientError => e
# 502-503 errors happen frequently from LGY endpoint at the time of implementation
# and have not been corrected yet. We would like to seperate these from our monitoring for now
# See https://github.com/department-of-veterans-affairs/va.gov-team/issues/90411
# and https://github.com/department-of-veterans-affairs/va.gov-team/issues/91111
if [503, 504].include?(e.status)
Rails.logger.info('LGY server unavailable or unresponsive',
{ status: e.status, messsage: e.message, body: e.body })
else
Rails.logger.error('LGY API returned error', { status: e.status, messsage: e.message, body: e.body })
end
raise e
end
def regional_office
[]
end
private
# rubocop:disable Metrics/MethodLength
def prepare_form_data
postal_code, postal_code_suffix = parsed_form['applicantAddress']['postalCode'].split('-', 2)
form_copy = {
'status' => 'SUBMITTED',
'veteran' => {
'firstName' => parsed_form['fullName']['first'],
'middleName' => parsed_form['fullName']['middle'] || '',
'lastName' => parsed_form['fullName']['last'],
'suffixName' => parsed_form['fullName']['suffix'] || '',
'dateOfBirth' => parsed_form['dateOfBirth'],
'vetAddress1' => parsed_form['applicantAddress']['street'],
'vetAddress2' => parsed_form['applicantAddress']['street2'] || '',
'vetCity' => parsed_form['applicantAddress']['city'],
'vetState' => parsed_form['applicantAddress']['state'],
'vetZip' => postal_code,
'vetZipSuffix' => postal_code_suffix,
'mailingAddress1' => parsed_form['applicantAddress']['street'],
'mailingAddress2' => parsed_form['applicantAddress']['street2'] || '',
'mailingCity' => parsed_form['applicantAddress']['city'],
'mailingState' => parsed_form['applicantAddress']['state'],
'mailingZip' => postal_code,
'mailingZipSuffix' => postal_code_suffix || '',
'contactPhone' => parsed_form['contactPhone'],
'contactEmail' => parsed_form['contactEmail'],
'vaLoanIndicator' => parsed_form['vaLoanIndicator'],
'vaHomeOwnIndicator' => (parsed_form['relevantPriorLoans'] || []).any? { |obj| obj['propertyOwned'] },
# parsed_form['identity'] can be: 'VETERAN', 'ADSM', 'NADNA', 'DNANA', or 'DRNA'.
'activeDutyIndicator' => parsed_form['identity'] == 'ADSM',
'disabilityIndicator' => false
},
'relevantPriorLoans' => [],
'periodsOfService' => []
}
relevant_prior_loans(form_copy) if parsed_form.key?('relevantPriorLoans')
periods_of_service(form_copy) if parsed_form.key?('periodsOfService')
update(form: form_copy.to_json)
form_copy
end
# rubocop:enable Metrics/MethodLength
def lgy_service
@lgy_service ||= LGY::Service.new(edipi: @edipi, icn: @icn)
end
# rubocop:disable Metrics/MethodLength
def relevant_prior_loans(form_copy)
parsed_form['relevantPriorLoans'].each do |loan_info|
property_zip, property_zip_suffix = loan_info['propertyAddress']['propertyZip'].split('-', 2)
form_copy['relevantPriorLoans'] << {
'vaLoanNumber' => loan_info['vaLoanNumber'].to_s,
'startDate' => loan_info['dateRange']['from'],
'paidOffDate' => loan_info['dateRange']['to'],
'loanAmount' => loan_info['loanAmount'],
'loanEntitlementCharged' => loan_info['loanEntitlementCharged'],
# propertyOwned also maps to the the stillOwn indicator on the LGY side
'propertyOwned' => loan_info['propertyOwned'] || false,
# In UI: "A one-time restoration of entitlement"
# In LGY: "One Time Resto"
'oneTimeRestorationRequested' => loan_info['intent'] == 'ONETIMERESTORATION',
# In UI: "An Interest Rate Reduction Refinance Loan (IRRRL) to refinance the balance of a current VA home loan"
# In LGY: "IRRRL Ind"
'irrrlRequested' => loan_info['intent'] == 'IRRRL',
# In UI: "A regular cash-out refinance of a current VA home loan"
# In LGY: "Cash Out Refi"
'cashoutRefinaceRequested' => loan_info['intent'] == 'REFI',
# In UI: "An entitlement inquiry only"
# In LGY: "Entitlement Inquiry Only"
'noRestorationEntitlementIndicator' => loan_info['intent'] == 'INQUIRY',
# LGY has requested `homeSellIndicator` always be null
'homeSellIndicator' => nil,
'propertyAddress1' => loan_info['propertyAddress']['propertyAddress1'],
'propertyAddress2' => loan_info['propertyAddress']['propertyAddress2'] || '',
'propertyCity' => loan_info['propertyAddress']['propertyCity'],
'propertyState' => loan_info['propertyAddress']['propertyState'],
# confirmed OK to omit propertyCounty, but LGY still requires a string
'propertyCounty' => '',
'propertyZip' => property_zip,
'propertyZipSuffix' => property_zip_suffix || ''
}
end
end
# rubocop:enable Metrics/MethodLength
def periods_of_service(form_copy)
parsed_form['periodsOfService'].each do |service_info|
# values from the FE for military_branch are:
# ["Air Force", "Air Force Reserve", "Air National Guard", "Army", "Army National Guard", "Army Reserve",
# "Coast Guard", "Coast Guard Reserve", "Marine Corps", "Marine Corps Reserve", "Navy", "Navy Reserve"]
# these need to be formatted because LGY only accepts [ARMY, NAVY, MARINES, AIR_FORCE, COAST_GUARD, OTHER]
# and then we have to pass in ACTIVE_DUTY or RESERVE_NATIONAL_GUARD for service_type
military_branch = service_info['serviceBranch'].parameterize.underscore.upcase
service_type = 'ACTIVE_DUTY'
# "Marine Corps" must be converted to "Marines" here, so that the `.any`
# block below can convert "Marine Corps" and "Marine Corps Reserve" to
# "MARINES", to meet LGY's requirements.
military_branch = military_branch.gsub('MARINE_CORPS', 'MARINES')
%w[RESERVE NATIONAL_GUARD].any? do |service_branch|
next unless military_branch.include?(service_branch)
index = military_branch.index('_NATIONAL_GUARD') || military_branch.index('_RESERVE')
military_branch = military_branch[0, index]
# "Air National Guard", unlike "Air Force Reserve", needs to be manually
# transformed to AIR_FORCE here, to meet LGY's requirements.
military_branch = 'AIR_FORCE' if military_branch == 'AIR'
service_type = 'RESERVE_NATIONAL_GUARD'
end
form_copy['periodsOfService'] << {
'enteredOnDuty' => service_info['dateRange']['from'],
'releasedActiveDuty' => service_info['dateRange']['to'],
'militaryBranch' => military_branch,
'serviceType' => service_type,
'disabilityIndicator' => false
}
end
end
def process_attachments!
supporting_documents = parsed_form['files']
if supporting_documents.present?
files = PersistentAttachment.where(guid: supporting_documents.pluck('confirmationCode'))
files.find_each { |f| f.update(saved_claim_id: id) }
prepare_document_data
end
end
def prepare_document_data
persistent_attachments.each do |attachment|
file_extension = File.extname(URI.parse(attachment.file.url).path)
claim_file_data =
parsed_form['files'].find { |f| f['confirmationCode'] == attachment['guid'] } ||
{ 'attachmentType' => '', 'attachmentDescription' => '' }
if %w[.jpg .jpeg .png .pdf].include? file_extension.downcase
file_path = Common::FileHelpers.generate_clamav_temp_file(attachment.file.read)
File.rename(file_path, "#{file_path}#{file_extension}")
file_path = "#{file_path}#{file_extension}"
document_data = {
# This is one of the options in the "Document Type" dropdown on the
# "Your supporting documents" step of the COE form. E.g. "Discharge or
# separation papers (DD214)"
'documentType' => claim_file_data['attachmentType'],
# This is the vet's own description of a document, after selecting
# "other" as the `attachmentType`.
'description' => claim_file_data['attachmentDescription'],
'contentsBase64' => Base64.encode64(File.read(file_path)),
'fileName' => attachment.file.metadata['filename']
}
lgy_service.post_document(payload: document_data)
Common::FileHelpers.delete_file_if_exists(file_path)
end
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/saved_claim/notice_of_disagreement.rb
|
# frozen_string_literal: true
class SavedClaim::NoticeOfDisagreement < SavedClaim
has_one :appeal_submission, class_name: 'AppealSubmission', foreign_key: :submitted_appeal_uuid, primary_key: :guid,
dependent: nil, inverse_of: :saved_claim_nod, required: false
FORM = '10182'
def form_matches_schema
return unless form_is_string
schema = VetsJsonSchema::SCHEMAS['NOD-CREATE-REQUEST-BODY_V1']
schema.delete '$schema' # workaround for JSON::Schema::SchemaError (Schema not found)
errors = JSON::Validator.fully_validate(schema, parsed_form)
unless errors.empty?
Rails.logger.warn("SavedClaim: schema validation errors detected for form #{FORM}", guid:, count: errors.count)
end
true # allow storage of all requests for debugging
rescue JSON::Schema::ReadFailed => e
Rails.logger.warn("SavedClaim: form_matches_schema error raised for form #{FORM}", guid:, error: e.message)
true
end
def process_attachments!
# Inherited from SavedClaim. Disabling since this claim handles attachments separately.
raise NotImplementedError, 'Not Implemented for Form 10182'
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/saved_claim/education_career_counseling_claim.rb
|
# frozen_string_literal: true
require 'vets/shared_logging'
class SavedClaim::EducationCareerCounselingClaim < CentralMailClaim
include Vets::SharedLogging
FORM = '28-8832'
def regional_office
[]
end
def send_to_benefits_intake!
form_copy = parsed_form
if form_copy['veteranSocialSecurityNumber'].blank?
claimant_info = parsed_form['claimantInformation']
form_copy['veteranSocialSecurityNumber'] = claimant_info['ssn'] || claimant_info['veteranSocialSecurityNumber']
update(form: form_copy.to_json)
end
log_message_to_sentry(guid, :warn, { attachment_id: guid }, { team: 'vfs-ebenefits' })
log_message_to_rails(guid, :warn)
process_attachments!
end
def process_attachments!
refs = attachment_keys.map { |key| Array(open_struct_form.send(key)) }.flatten
files = PersistentAttachment.where(guid: refs.map(&:confirmationCode))
files.find_each { |f| f.update(saved_claim_id: id) }
Lighthouse::SubmitBenefitsIntakeClaim.new.perform(id)
end
def business_line
'EDU'
end
# this failure email is not the ideal way to handle the Notification Emails as
# part of the ZSF work, but with the initial timeline it handles the email as intended.
# Future work will be integrating into the Va Notify common lib:
# https://github.com/department-of-veterans-affairs/vets-api/blob/master/lib/veteran_facing_services/notification_email.rb
def send_failure_email(email)
if email.present?
VANotify::EmailJob.perform_async(
email,
Settings.vanotify.services.va_gov.template_id.form27_8832_action_needed_email,
{
'first_name' => parsed_form.dig('claimantInformation', 'fullName', 'first')&.upcase.presence,
'date_submitted' => Time.zone.today.strftime('%B %d, %Y'),
'confirmation_number' => confirmation_number
}
)
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/saved_claim/form214192.rb
|
# frozen_string_literal: true
class SavedClaim::Form214192 < SavedClaim
FORM = '21-4192'
DEFAULT_ZIP_CODE = '00000'
validates :form, presence: true
def form_schema
schema = JSON.parse(Openapi::Requests::Form214192::FORM_SCHEMA.to_json)
schema['components'] = JSON.parse(Openapi::Components::ALL.to_json)
schema
end
def process_attachments!
# Form 21-4192 does not support attachments in MVP
# This form is completed by employers providing employment information
# No supporting documents are collected as part of the form submission
Lighthouse::SubmitBenefitsIntakeClaim.perform_async(id)
end
def send_confirmation_email
# Email functionality not included in MVP
# employer_email = parsed_form.dig('employmentInformation', 'employerEmail')
# return unless employer_email
# VANotify::EmailJob.perform_async(
# employer_email,
# Settings.vanotify.services.va_gov.template_id.form214192_confirmation,
# {
# 'employer_name' => employer_name,
# 'veteran_name' => veteran_name,
# 'confirmation_number' => confirmation_number,
# 'date_submitted' => created_at.strftime('%B %d, %Y')
# }
# )
end
# SavedClaims require regional_office to be defined
def regional_office
[].freeze
end
# Required for Lighthouse Benefits Intake API submission
# CMP = Compensation (for disability claims)
def business_line
'CMP'
end
# VBMS document type for employment information
def document_type
119 # Request for Employment Information
end
def attachment_keys
# Form 21-4192 does not support attachments in MVP
[].freeze
end
# Override to_pdf to add employer signature stamp
# This ensures the signature is included in both the download_pdf endpoint
# and the Lighthouse Benefits Intake submission
def to_pdf(file_name = nil, fill_options = {})
pdf_path = PdfFill::Filler.fill_form(self, file_name, fill_options)
PdfFill::Forms::Va214192.stamp_signature(pdf_path, parsed_form)
end
def metadata_for_benefits_intake
{ veteranFirstName: parsed_form.dig('veteranInformation', 'fullName', 'first'),
veteranLastName: parsed_form.dig('veteranInformation', 'fullName', 'last'),
fileNumber: parsed_form.dig('veteranInformation', 'vaFileNumber') || parsed_form.dig('veteranInformation', 'ssn'),
zipCode: zip_code_for_metadata,
businessLine: business_line }
end
private
def zip_code_for_metadata
parsed_form.dig('employmentInformation', 'employerAddress', 'postalCode') || DEFAULT_ZIP_CODE
end
def employer_name
parsed_form.dig('employmentInformation', 'employerName') || 'Employer'
end
def veteran_name
first = parsed_form.dig('veteranInformation', 'fullName', 'first')
last = parsed_form.dig('veteranInformation', 'fullName', 'last')
"#{first} #{last}".strip.presence || 'Veteran'
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/saved_claim/dependency_claim.rb
|
# frozen_string_literal: true
require 'claims_api/vbms_uploader'
require 'pdf_utilities/datestamp_pdf'
require 'dependents/monitor'
require 'dependents/notification_email'
class SavedClaim::DependencyClaim < CentralMailClaim
FORM = '686C-674'
STUDENT_ATTENDING_COLLEGE_KEYS = %w[
student_information
student_name_and_ssn
student_address_marriage_tuition
last_term_school_information
school_information
program_information
current_term_dates
student_earnings_from_school_year
student_networth_information
student_expected_earnings_next_year
student_does_have_networth
student_does_earn_income
student_will_earn_income_next_year
student_did_attend_school_last_term
].freeze
DEPENDENT_CLAIM_FLOWS = %w[
report_death
report_divorce
add_child
report_stepchild_not_in_household
report_marriage_of_child_under18
child_marriage
report_child18_or_older_is_not_attending_school
add_spouse
add_disabled_child
].freeze
FORM686 = '21-686c'
FORM674 = '21-674'
FORM_COMBO = '686c-674'
validate :validate_686_form_data, on: :run_686_form_jobs
validate :address_exists
attr_accessor :use_v2
after_initialize do
self.form_id = if use_v2 || form_id == '686C-674-V2'
'686C-674-V2'
else
self.class::FORM.upcase
end
end
def pdf_overflow_tracking
track_each_pdf_overflow(use_v2 ? '686C-674-V2' : '686C-674') if submittable_686?
track_each_pdf_overflow(use_v2 ? '21-674-V2' : '21-674') if submittable_674?
rescue => e
monitor.track_pdf_overflow_tracking_failure(e)
end
def track_each_pdf_overflow(subform_id)
filenames = []
if subform_id == '21-674-V2'
parsed_form['dependents_application']['student_information']&.each do |student|
filenames << to_pdf(form_id: subform_id, student:)
end
else
filenames << to_pdf(form_id: subform_id)
end
filenames.each do |filename|
monitor.track_pdf_overflow(subform_id) if filename.end_with?('_final.pdf')
end
ensure
filenames.each do |filename|
Common::FileHelpers.delete_file_if_exists(filename)
end
end
def process_pdf(pdf_path, timestamp = nil, form_id = nil, iterator = nil)
processed_pdf = PDFUtilities::DatestampPdf.new(pdf_path).run(
text: 'Application Submitted on site',
x: 400,
y: 675,
text_only: true, # passing as text only because we override how the date is stamped in this instance
timestamp:,
page_number: %w[686C-674 686C-674-V2].include?(form_id) ? 6 : 0,
template: "lib/pdf_fill/forms/pdfs/#{form_id}.pdf",
multistamp: true
)
renamed_path = iterator.present? ? "tmp/pdfs/#{form_id}_#{id}_#{iterator}_final.pdf" : "tmp/pdfs/#{form_id}_#{id}_final.pdf" # rubocop:disable Layout/LineLength
File.rename(processed_pdf, renamed_path) # rename for vbms upload
renamed_path # return the renamed path
end
def add_veteran_info(va_file_number_with_payload)
parsed_form.merge!(va_file_number_with_payload)
end
def formatted_686_data(va_file_number_with_payload)
partitioned_686_674_params[:dependent_data].merge(va_file_number_with_payload).with_indifferent_access
end
def formatted_674_data(va_file_number_with_payload)
partitioned_686_674_params[:college_student_data].merge(va_file_number_with_payload).with_indifferent_access
end
def submittable_686?
submitted_flows = DEPENDENT_CLAIM_FLOWS.map { |flow| parsed_form['view:selectable686_options'].include?(flow) }
return true if submitted_flows.include?(true)
false
end
def submittable_674?
# check if report674 is present and then check if it's true to avoid hash break.
parsed_form['view:selectable686_options']&.include?('report674') &&
parsed_form['view:selectable686_options']['report674']
end
def address_exists
if parsed_form.dig('dependents_application', 'veteran_contact_information', 'veteran_address').blank?
errors.add(:parsed_form, "Veteran address can't be blank")
end
end
def validate_686_form_data
errors.add(:parsed_form, "SSN can't be blank") if parsed_form['veteran_information']['ssn'].blank?
errors.add(:parsed_form, "Dependent application can't be blank") if parsed_form['dependents_application'].blank?
end
# SavedClaims require regional_office to be defined
def regional_office
[]
end
# Run after a claim is saved, this processes any files/supporting documents that are present
def process_attachments!
child_documents = parsed_form.dig('dependents_application', 'child_supporting_documents')
spouse_documents = parsed_form.dig('dependents_application', 'spouse_supporting_documents')
# add the two arrays together but also account for nil arrays
supporting_documents = [child_documents, spouse_documents].compact.reduce([], :|)
if supporting_documents.present?
files = PersistentAttachment.where(guid: supporting_documents.pluck('confirmation_code'))
files.find_each { |f| f.update(saved_claim_id: id) }
end
end
def document_type
148
end
def form_matches_schema
return if Flipper.enabled?(:dependents_bypass_schema_validation)
return unless form_is_string
schema = VetsJsonSchema::SCHEMAS[form_id]
schema_errors = validate_schema(schema)
unless schema_errors.empty?
Rails.logger.error('SavedClaim schema failed validation.',
{ form_id:, errors: schema_errors })
end
validation_errors = validate_form(schema)
validation_errors.each do |e|
errors.add(e[:fragment], e[:message])
e[:errors]&.flatten(2)&.each { |nested| errors.add(nested[:fragment], nested[:message]) if nested.is_a? Hash }
end
unless validation_errors.empty?
Rails.logger.error('SavedClaim form did not pass validation', { form_id:, guid:, errors: validation_errors })
end
schema_errors.empty? && validation_errors.empty?
end
def to_pdf(form_id: FORM, student: nil)
original_form_id = self.form_id
self.form_id = form_id
PdfFill::Filler.fill_form(self, nil, { created_at:, student: })
rescue => e
monitor.track_to_pdf_failure(e, form_id)
raise e
ensure
self.form_id = original_form_id
end
def send_failure_email(email)
# if the claim is both a 686c and a 674, send a combination email.
# otherwise, check to see which individual type it is and send the corresponding email.
first_name = parsed_form.dig('dependents_application', 'veteran_information', 'full_name', 'first')&.upcase.presence
personalisation = {
'first_name' => first_name,
'date_submitted' => Time.zone.today.strftime('%B %d, %Y'),
'confirmation_number' => confirmation_number
}
template_id = if submittable_686? && submittable_674?
Settings.vanotify.services.va_gov.template_id.form21_686c_674_action_needed_email
elsif submittable_686?
Settings.vanotify.services.va_gov.template_id.form21_686c_action_needed_email
elsif submittable_674?
Settings.vanotify.services.va_gov.template_id.form21_674_action_needed_email
else
Rails.logger.error('Email template cannot be assigned for SavedClaim', saved_claim_id: id)
nil
end
if email.present? && template_id.present?
Dependents::Form686c674FailureEmailJob.perform_async(id, email, template_id, personalisation)
end
end
##
# Determine if claim is a 686, 674, both, or unknown
#
def claim_form_type
return FORM_COMBO if submittable_686? && submittable_674?
return FORM686 if submittable_686?
FORM674 if submittable_674?
rescue => e
monitor.track_unknown_claim_type(e)
nil
end
##
# VANotify job to send Submitted/in-Progress email to veteran
#
def send_submitted_email(user = nil)
type = claim_form_type
if type == FORM686
Dependents::NotificationEmail.new(id, user).deliver(:submitted686)
elsif type == FORM674
Dependents::NotificationEmail.new(id, user).deliver(:submitted674)
else
# Combo or unknown form types use combo email
Dependents::NotificationEmail.new(id, user).deliver(:submitted686c674)
end
monitor.track_send_submitted_email_success(user&.user_account_uuid)
rescue => e
monitor.track_send_submitted_email_failure(e, user&.user_account_uuid)
end
##
# VANotify job to send Received/Confirmation email to veteran
#
def send_received_email(user = nil)
type = claim_form_type
if type == FORM686
Dependents::NotificationEmail.new(id, user).deliver(:received686)
elsif type == FORM674
Dependents::NotificationEmail.new(id, user).deliver(:received674)
else
# Combo or unknown form types use combo email
Dependents::NotificationEmail.new(id, user).deliver(:received686c674)
end
monitor.track_send_received_email_success(user&.user_account_uuid)
rescue => e
monitor.track_send_received_email_failure(e, user&.user_account_uuid)
end
def monitor
@monitor ||= Dependents::Monitor.new(id)
end
private
def partitioned_686_674_params
dependent_data = parsed_form
student_data = dependent_data['dependents_application'].extract!(*STUDENT_ATTENDING_COLLEGE_KEYS)
veteran_data = dependent_data['dependents_application'].slice('household_income', 'veteran_contact_information')
college_student_data = { 'dependents_application' => student_data.merge!(veteran_data) }
{ college_student_data:, dependent_data: }
end
def validate_form(schema)
camelized_data = deep_camelize_keys(parsed_form)
errors = JSONSchemer.schema(schema).validate(camelized_data).to_a
return [] if errors.empty?
reformatted_schemer_errors(errors)
end
def deep_camelize_keys(data)
case data
when Hash
data.transform_keys { |key| key.to_s.camelize(:lower) }
.transform_values { |value| deep_camelize_keys(value) }
when Array
data.map { |item| deep_camelize_keys(item) }
else
data
end
end
end
|
0
|
code_files/vets-api-private/app/models
|
code_files/vets-api-private/app/models/saved_claim/dependency_verification_claim.rb
|
# frozen_string_literal: true
class SavedClaim::DependencyVerificationClaim < CentralMailClaim
FORM = '21-0538'
def regional_office
[]
end
def send_to_central_mail!
form_copy = parsed_form
form_copy['veteranSocialSecurityNumber'] = parsed_form.dig('dependencyVerification', 'veteranInformation', 'ssn')
form_copy['veteranFullName'] = parsed_form.dig('dependencyVerification', 'veteranInformation', 'fullName')
form_copy['veteranAddress'] = ''
update(form: form_copy.to_json)
Rails.logger.warn('Attachment processed', { attachment_id: guid, team: 'vfs-ebenefits' })
process_attachments!
end
def add_claimant_info(user)
updated_form = parsed_form
updated_form.merge!(
{
'dependencyVerification' => {
'updateDiaries' => true,
'veteranInformation' => {
'fullName' => {
'first' => user.first_name,
'middleInitial' => user.middle_name,
'last' => user.last_name
},
'ssn' => user.ssn,
'dateOfBirth' => user.birth_date,
'email' => user.email
}
}
}
).except!('update_diaries')
update(form: updated_form.to_json)
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.