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/swagger/swagger/requests
|
code_files/vets-api-private/app/swagger/swagger/requests/gibct/institution_programs.rb
|
# frozen_string_literal: true
module Swagger
module Requests
module Gibct
class InstitutionPrograms
include Swagger::Blocks
swagger_path '/v0/gi/institution_programs/autocomplete' do
operation :get do
key :description, 'Retrieves institution programs beginning with a set of letters'
key :operationId, 'gibctInstitutionProgramsAutocomplete'
key :tags, %w[gi_bill_institutions]
parameter name: :term, in: :query,
required: true, type: :string, description: 'start of an institution program name'
response 200 do
key :description, 'autocomplete response'
schema do
key :$ref, :GibctInstitutionProgramsAutocomplete
end
end
end
end
swagger_path '/v0/gi/institution_programs/search' do
operation :get do
key :description, 'Retrieves institution programs with partial match'
key :operationId, 'gibctInstitutionProgramsSearch'
key :tags, %w[gi_bill_institutions]
parameter name: :term,
in: :query,
required: false,
type: :string,
description: '(partial) institution program name, city, or facility code'
response 200 do
key :description, 'search response'
schema do
key :$ref, :GibctInstitutionProgramsSearch
end
end
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/swagger/swagger/requests
|
code_files/vets-api-private/app/swagger/swagger/requests/gibct/yellow_ribbon_programs.rb
|
# frozen_string_literal: true
module Swagger
module Requests
module Gibct
class YellowRibbonPrograms
include Swagger::Blocks
swagger_path '/v0/gi/yellow_ribbon_programs' do
operation :get do
key :description, 'Retrieves Yellow Ribbon Programs with partial match'
key :operationId, 'gibctYellowRibbonPrograms'
key :tags, %w[gi_bill_institutions]
parameter description: 'Filter results by the name of a city.',
in: :query,
name: :city,
required: false,
type: :string
parameter description: 'Filter results to only include unlimited contribution amounts.',
enum: ['unlimited'],
in: :query,
name: :contribution_amount,
required: false,
type: :string
parameter description: 'Filter results by a country abbreviation (e.g. "usa").',
in: :query,
name: :country,
required: false,
type: :string
parameter description: 'Filter results to only include unlimited eligible students.',
enum: ['unlimited'],
in: :query,
name: :number_of_students,
required: false,
type: :string
parameter description: 'The page of results. It must be greater than 0 if used.',
in: :query,
name: :page,
required: false,
type: :number
parameter description: 'Number of results to include per page. It must be greater than 0 if used.',
in: :query,
name: :per_page,
required: false,
type: :string
parameter description: 'Filter results by the name of the Institution.',
in: :query,
name: :name,
required: false,
type: :string
parameter description: 'Sort results by a Yellow Ribbon Program attribute.',
enum: %w[city contribution_amount country number_of_students institution state],
in: :query,
name: :sort_by,
required: false,
type: :string
parameter description: 'Sorts results either ascending or descending.',
enum: %w[desc asc],
in: :query,
name: :sort_direction,
required: false,
type: :string
parameter description: 'Filter results by a State abbreviation (e.g. "co").',
in: :query,
name: :state,
required: false,
type: :string
response 200 do
key :description, 'response'
schema do
key :$ref, :GibctYellowRibbonPrograms
end
end
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/swagger/swagger/requests
|
code_files/vets-api-private/app/swagger/swagger/requests/contact_us/inquiries.rb
|
# frozen_string_literal: true
module Swagger
module Requests
module ContactUs
class Inquiries
include Swagger::Blocks
swagger_path '/v0/contact_us/inquiries' do
operation :post do
extend Swagger::Responses::ValidationError
key :description, 'Create an inquiry'
key :operationId, 'createsAnInquiry'
key :tags, %w[contact_us]
parameter :optional_authorization
parameter do
key :name, :body
key :in, :body
key :description, 'The properties to create an inquiry'
key :required, true
schema do
property :inquiry do
property :form do
key :type, :string
key :description, 'Should conform to vets-json-schema (https://github.com/department-of-veterans-affairs/vets-json-schema)'
end
end
end
end
response 201 do
key :description, 'Successful inquiry creation'
schema do
key :$ref, :SuccessfulInquiryCreation
end
end
response 501 do
key :description, 'Feature toggled off'
end
end
operation :get do
extend Swagger::Responses::AuthenticationError
key :description, 'Get a list of inquiries sent by user'
key :operationId, 'getInquiries'
key :tags, %w[contact_us]
parameter :authorization
response 200 do
key :description, 'Response is OK'
schema do
key :$ref, :InquiriesList
end
end
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/swagger/swagger/requests
|
code_files/vets-api-private/app/swagger/swagger/requests/contact_us/inquiries_list.rb
|
# frozen_string_literal: true
module Swagger
module Requests
module ContactUs
class InquiriesList
include Swagger::Blocks
swagger_path '/v0/contact_us/inquiries' do
operation :get do
extend Swagger::Responses::AuthenticationError
key :description, 'Get a list of inquiries sent by user'
key :operationId, 'getInquiries'
key :tags, %w[contact_us]
parameter :authorization
response 200 do
key :description, 'Response is OK'
schema do
key :$ref, :InquiriesList
end
end
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/swagger/swagger/requests
|
code_files/vets-api-private/app/swagger/swagger/requests/mdot/supplies.rb
|
# frozen_string_literal: true
# app/controllers/v0/mdot/suppliesc_controller.rb
module Swagger
module Requests
module MDOT
class Supplies
include Swagger::Blocks
swagger_path '/v0/mdot/supplies' do
operation :post do
key :description, 'Create a MDOT supply order'
key :operationId, 'addMdotOrder'
key :tags, %w[mdot]
extend Swagger::Responses::AuthenticationError
parameter :authorization
key :produces, ['application/json']
key :consumes, ['application/json']
parameter do
key :name, :order_input
key :in, :body
key :description, 'Order input'
key :required, true
schema do
key :type, :object
property :use_permanent_address, type: :boolean, example: true
property :use_temporary_address, type: :boolean, example: false
property :vet_email, type: :string, example: 'vet1@va.gov'
property :order do
key :type, :array
items do
key :type, :object
property :product_id, type: :integer, example: 2499
end
end
property :permanent_address do
key :type, :object
property :is_military, type: :boolean, example: false
property :street, type: :string, example: '125 SOME RD'
property :street2, type: :string, example: 'APT 101'
property :city, type: :string, example: 'DENVER'
property :state, type: :string, example: 'CO'
property :country, type: :string, example: 'United States'
property :postal_code, type: :string, example: '11111'
end
property :temporary_address do
key :type, :object
property :is_military, type: :boolean, example: false
property :street, type: :string, example: '17250 w colfax ave'
property :street2, type: :string, example: 'a-204'
property :city, type: :string, example: 'Golden'
property :state, type: :string, example: 'CO'
property :country, type: :string, example: 'United States'
property :postal_code, type: :string, example: '80401'
end
end
end
response 200 do
key :description, 'Response is OK'
schema do
key :type, :array
items do
key :type, :object
property :product_id, type: :integer, example: 2499
property :order_id, type: :integer, example: 1001
property :status,
type: :string,
example: 'Order Processed',
enum: [
'Order Processed',
'Order Pending',
'Unable to order item since the last order was less than 5 months ago.'
]
end
end
end
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/swagger/swagger/requests
|
code_files/vets-api-private/app/swagger/swagger/requests/my_va/submission_statuses.rb
|
# app/controllers/v0/my_va/submission_statuses_controller.rb
# frozen_string_literal: true
module Swagger
module Requests
module MyVA
class SubmissionStatuses
include Swagger::Blocks
swagger_path '/v0/my_va/submission_statuses' do
operation :get do
key :description, 'Get list of submitted forms for the current session'
key :operationId, 'getSubmissionStatuses'
key :tags, %w[
my_va
]
parameter :authorization
key :produces, ['application/json']
response 200 do
key :description, 'submitted forms and statuses'
schema do
key :type, :object
property :data do
key :type, :array
items do
key :required, %i[
id
type
attributes
]
property :id, type: :string, example: '3b03b5a0-3ad9-4207-b61e-3a13ed1c8b80',
description: 'Form submission UID'
property :type, type: :string, example: 'submission_status', description: 'type of request'
property :attributes do
key :$ref, :SubmissionStatusAttrs
end
end
end
end
end
response 296 do
key :description, 'submitted forms but errors occured looking up statuses from lighthouse'
schema do
key :type, :object
key :required, %i[data errors]
property :data do
key :type, :array
items do
key :required, %i[
id
type
attributes
]
property :id, type: :string, example: '3b03b5a0-3ad9-4207-b61e-3a13ed1c8b80',
description: 'Form submission UID'
property :type, type: :string, example: 'submission_status', description: 'type of request'
property :attributes do
key :$ref, :SubmissionStatusAttrs
end
end
end
property :errors do
key :type, :array
items do
key :required, %i[
status
source
title
detail
]
property :status, type: :integer, example: 429, description: 'Error code'
property :source, type: :string, example: 'Lighthouse - Benefits Intake API',
description: 'Error source'
property :title, type: :string, example: 'Form Submission Status: Too Many Requests',
description: 'Error description'
property :detail, type: :string, example: 'API rate limit exceeded', description: 'Error details'
end
end
end
end
end
end
swagger_schema :SubmissionStatusAttrs do
key :type, :object
key :description, 'submitted form attributes'
property :id, type: :string, example: '3b03b5a0-3ad9-4207-b61e-3a13ed1c8b80',
description: 'Submitted form UID from lighthouse'
property :detail, type: [:string, 'null'], example: '',
description: 'Error details (only when errors are present)'
property :form_type, type: :string, example: '21-0845', description: 'The type of form'
property :message, type: [:string, 'null'], example: 'Descriptive message'
property :status, type: [:string, 'null'], enum: [
nil,
'pending',
'uploaded',
'received',
'processing',
'success',
'vbms',
'error',
'expired'
], example: 'received', description: 'The current status of the submission'
property :created_at, type: :string, example: '2023-12-15T20:40:47.583Z',
description: 'The submission record created in VA.gov'
property :updated_at, type: [:string, 'null'], example: '2023-12-15T20:40:54.474Z',
description: 'The last time the submission status was updated'
property :pdf_support, type: :boolean, example: true,
description: 'True if submission supports archived pdf downloads'
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/swagger/swagger/requests
|
code_files/vets-api-private/app/swagger/swagger/requests/appeals/appeals.rb
|
# frozen_string_literal: true
require 'decision_review/schemas'
module Swagger
module Requests
module Appeals
class Appeals
include Swagger::Blocks
swagger_path '/v0/appeals' do
operation :get do
extend Swagger::Responses::AuthenticationError
key :description, 'returns list of appeals for a user'
key :operationId, 'getAppeals'
key :tags, %w[benefits_status]
parameter :authorization
response 200 do
key :description, '200 passes the response from the upstream appeals API'
schema '$ref': :Appeals
end
response 401 do
key :description, 'User is not authenticated (logged in)'
schema '$ref': :Errors
end
response 403 do
key :description, 'Forbidden: user is not authorized for appeals'
schema '$ref': :Errors
end
response 404 do
key :description, 'Not found: appeals not found for user'
schema '$ref': :Errors
end
response 422 do
key :description, 'Unprocessable Entity: one or more validations has failed'
schema '$ref': :Errors
end
response 502 do
key :description, 'Bad Gateway: the upstream appeals app returned an invalid response (500+)'
schema '$ref': :Errors
end
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/swagger/swagger/requests
|
code_files/vets-api-private/app/swagger/swagger/requests/form1010cg/attachments.rb
|
# frozen_string_literal: true
module Swagger
module Requests
module Form1010cg
class Attachments
include Swagger::Blocks
swagger_path '/v0/form1010cg/attachments' do
operation :post do
extend Swagger::Responses::ValidationError
extend Swagger::Responses::BadRequestError
key :description, 'Upload Power of Attorney attachment for a caregivers assistance claim.'
parameter do
key :name, :attachment
key :in, :body
key :description, 'The document data'
key :required, true
schema do
key :required, %i[file_data]
property :file_data, type: :string, example: 'my-poa.png'
property :password, type: :string, example: 'MyPassword123'
end
end
response 200 do
key :description, 'Ok'
schema do
key :required, [:data]
property :data, type: :object do
key :required, %i[id type attributes]
property :id do
key :description, 'The record\'s identifier'
key :type, :string
key :example, '"67"'
end
property :type do
key :description, 'This is always "form1010cg_attachments"'
key :type, :string
key :example, 'form1010cg_attachments'
end
property :attributes, type: :object do
key :required, [:guid]
property :guid do
key :description, 'The document\'s GUID. To attach this document to a claim,\\
include this id the claim\'s submission payload.'
key :type, :string
key :example, '834d9f51-d0c7-4dc2-9f2e-9b722db98069'
end
end
end
end
end
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form_email_matches_profile_log.rb
|
# frozen_string_literal: true
class FormEmailMatchesProfileLog < ApplicationRecord
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/old_email.rb
|
# frozen_string_literal: true
require 'common/models/concerns/cache_aside'
class OldEmail < Common::RedisStore
redis_store REDIS_CONFIG[:old_email][:namespace]
redis_ttl REDIS_CONFIG[:old_email][:each_ttl]
redis_key :transaction_id
attribute :transaction_id, String
attribute :email, String
validates(:transaction_id, :email, presence: true)
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/personal_information_log.rb
|
# frozen_string_literal: true
class PersonalInformationLog < ApplicationRecord
scope :last_week, -> { where('created_at >= :date', date: 1.week.ago) }
has_kms_key
has_encrypted :data, type: :json, key: :kms_key, **lockbox_options
validates :error_class, presence: true
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form526_submission.rb
|
# frozen_string_literal: true
require 'evss/disability_compensation_form/form526_to_lighthouse_transform'
require 'sidekiq/form526_backup_submission_process/submit'
require 'logging/third_party_transaction'
require 'lighthouse/poll_form526_pdf'
require 'scopes/form526_submission_state'
class Form526Submission < ApplicationRecord
extend Logging::ThirdPartyTransaction::MethodWrapper
include Form526ClaimFastTrackingConcern
include Form526MPIConcern
include Scopes::Form526SubmissionState
wrap_with_logging(:start_evss_submission_job,
:enqueue_backup_submission,
:submit_form_4142,
:submit_uploads,
:submit_form_0781,
:submit_form_8940,
:upload_bdd_instructions,
:submit_flashes,
:poll_form526_pdf,
:cleanup,
additional_class_logs: { action: 'Begin as anciliary 526 submission' },
additional_instance_logs: {
saved_claim_id: %i[saved_claim id],
user_uuid: %i[user_uuid]
})
# A 526 disability compensation form record. This class is used to persist the post transformation form
# and track submission workflow steps.
#
# @!attribute id
# @return [Integer] auto-increment primary key.
# @!attribute user_uuid
# @return [String] points to the user's uuid from the identity provider.
# @!attribute saved_claim_id
# @return [Integer] the related saved claim id {SavedClaim::DisabilityCompensation}.
# @!attribute auth_headers_json
# @return [String] encrypted EVSS auth headers as JSON {EVSS::DisabilityCompensationAuthHeaders}.
# @!attribute form_json
# @return [String] encrypted form submission as JSON.
# @!attribute workflow_complete
# @return [Boolean] are all the steps (jobs {EVSS::DisabilityCompensationForm::Job}) of the submission
# workflow complete.
# @!attribute created_at
# @return [Timestamp] created at date.
# @!attribute updated_at
# @return [Timestamp] updated at date.
has_kms_key
has_encrypted :auth_headers_json, :birls_ids_tried, :form_json, key: :kms_key, **lockbox_options
belongs_to :saved_claim, class_name: 'SavedClaim::DisabilityCompensation', inverse_of: false
has_many :form526_job_statuses, dependent: :destroy
has_many :form526_submission_remediations, dependent: :destroy
belongs_to :user_account, dependent: nil
validates(:auth_headers_json, presence: true)
enum :backup_submitted_claim_status, { accepted: 0, rejected: 1, paranoid_success: 2 }
enum :submit_endpoint, { evss: 0, claims_api: 1, benefits_intake_api: 2 }
FORM_526 = 'form526'
FORM_526_UPLOADS = 'form526_uploads'
FORM_4142 = 'form4142'
FORM_0781 = 'form0781'
FORM_8940 = 'form8940'
FLASHES = 'flashes'
BIRLS_KEY = 'va_eauth_birlsfilenumber'
SUBMIT_FORM_526_JOB_CLASSES = %w[SubmitForm526AllClaim SubmitForm526].freeze
# MAX_PENDING_TIME aligns with the farthest out expectation given in the LH BI docs,
# plus 1 week to accomodate for edge cases and our sidekiq jobs
MAX_PENDING_TIME = 3.weeks
ZSF_DD_TAG_SERVICE = 'disability-application'
UPLOAD_DELAY_BASE = 60.seconds
UNIQUENESS_INCREMENT = 5
# the keys of the Toxic Exposure details for each section
TOXIC_EXPOSURE_DETAILS_MAPPING = {
'gulfWar1990Details' => %w[afghanistan bahrain egypt iraq israel jordan kuwait neutralzone oman qatar saudiarabia
somalia syria uae turkey waters airspace],
'gulfWar2001Details' => %w[djibouti lebanon uzbekistan yemen airspace],
'herbicideDetails' => %w[cambodia guam koreandemilitarizedzone johnston laos c123 thailand vietnam],
'otherExposuresDetails' => %w[asbestos chemical mos mustardgas radiation water],
'otherHerbicideLocations' => [],
'specifyOtherExposures' => []
}.freeze
# used to track in APMs between systems such as Lighthouse
# example: can be used as a search parameter in Datadog
# TODO: follow-up in ticket #93563 to make this more robust, i.e. attempts of jobs, etc.
def system_transaction_id
service_provider = saved_claim.parsed_form['startedFormVersion'].present? ? 'lighthouse' : 'evss'
"Form526Submission_#{id}, user_uuid: #{user_uuid}, service_provider: #{service_provider}"
end
# Called when the DisabilityCompensation form controller is ready to hand off to the backend
# submission process. Currently this passes directly to the retryable EVSS workflow, but if any
# one-time setup or workflow redirection (e.g. for Claims Fast-Tracking) needs to happen, it should
# go here and call start_evss_submission_job when done.
def start
log_max_cfi_metrics_on_submit
log_document_type_metrics
start_evss_submission_job
end
# Kicks off a retryable 526 submit workflow. The first step in a submission workflow is to submit
# an increase only or all claims form. Once the first job succeeds the batch will callback and run
# one (cleanup job) or more ancillary jobs such as uploading supporting evidence or submitting ancillary forms.
#
# @return [String] the job id of the first job in the batch, i.e the 526 submit job
#
def start_evss_submission_job
workflow_batch = Sidekiq::Batch.new
workflow_batch.on(
:success,
'Form526Submission#perform_ancillary_jobs_handler',
'submission_id' => id,
# Call get_first_name while the temporary User record still exists
'first_name' => get_first_name
)
job_ids = workflow_batch.jobs do
EVSS::DisabilityCompensationForm::SubmitForm526AllClaim.perform_async(id)
end
job_ids.first
end
# Runs start_evss_submission_job but first looks to see if the veteran has BIRLS IDs that previous start
# attempts haven't used before (if so, swaps one of those into auth_headers).
# If all BIRLS IDs for a veteran have been tried, does nothing and returns nil.
# Note: this assumes that the current BIRLS ID has been used (that `start` has been attempted once).
#
# @return [String] the job id of the first job in the batch, i.e the 526 submit job
# @return [NilClass] all BIRLS IDs for the veteran have been tried
#
def submit_with_birls_id_that_hasnt_been_tried_yet!(
extra_content_for_logs: {},
silence_errors_and_log: false
)
untried_birls_id = birls_ids_that_havent_been_tried_yet.first
return unless untried_birls_id
self.birls_id = untried_birls_id
save!
start_evss_submission_job
rescue => e
# 1) why have the 'silence_errors_and_log' option? (why not rethrow the error?)
# This method is primarily intended to be triggered by a running Sidekiq job that has hit a dead end
# (exhausted, or non-retryable error). One of the places this method is called is inside a
# `sidekiq_retries_exhausted` block. It seems like the value of self for that block won't be the
# Sidekiq job instance (so no access to the log_exception method). Also, rethrowing the error
# (and letting it bubble up to Sidekiq) might trigger the current job to retry (which we don't want).
raise unless silence_errors_and_log
Rails.logger.error('Form526Submission#submit_with_birls_id_that_hasnt_been_tried_yet! error',
error: e,
extra_content_for_logs: extra_content_for_logs.merge({ form526_submission_id: id }))
end
# Note that the User record is cached in Redis -- `User.redis_namespace_ttl`
def get_first_name
user&.first_name&.upcase.presence || auth_headers&.dig('va_eauth_firstName')&.upcase
end
# Checks against the User record first, and then resorts to checking the auth_headers
# for the name attributes if the User record doesn't exist or contain the full name
#
# @return [Hash] of the user's full name (first, middle, last, suffix)
#
def full_name
name_hash = user&.full_name_normalized
return name_hash if name_hash&.[](:first).present?
{ first: auth_headers&.dig('va_eauth_firstName')&.capitalize, middle: nil,
last: auth_headers&.dig('va_eauth_lastName')&.capitalize, suffix: nil }
end
# form_json is memoized here so call invalidate_form_hash after updating form_json
# @return [Hash] parsed version of the form json
#
def form
@form_hash ||= JSON.parse(form_json)
end
# Call this method to invalidate the memoized @form_hash variable after updating form_json.
# A hook that calls this method could be added so that we don't have to call this manually,
# see https://stackoverflow.com/questions/24314584/run-a-callback-only-if-an-attribute-has-changed-in-rails
def invalidate_form_hash
remove_instance_variable(:@form_hash) if instance_variable_defined?(:@form_hash)
end
# A 526 submission can include the 526 form submission, uploads, and ancillary items.
# This method returns a single item as JSON
#
# @param item [String] the item key
# @return [String] the requested form object as JSON
#
def form_to_json(item)
form[item].to_json
end
# @return [Hash] parsed auth headers
#
def auth_headers
@auth_headers_hash ||= JSON.parse(auth_headers_json)
end
# this method is for queuing up BIRLS ids in the birls_ids_tried hash,
# and can also be used for initializing birls_ids_tried.
# birls_ids_tried has this shape:
# {
# birls_id => [timestamp, timestamp, ...],
# birls_id => [timestamp, timestamp, ...], # in practice, will be only 1 timestamp
# ...
# }
# where each timestamp notes when a submissison job (start) was started
# with that BIRLS id (birls_id_tried keeps track of which BIRLS id
# have been tried so far).
# add_birls_ids does not overwrite birls_ids_tried.
# example:
# > sub.birls_ids_tried = { '111' => ['2021-01-01T0000Z'] }
# > sub.add_birls_ids ['111', '222', '333']
# > pp sub.birls_ids_tried
# {
# '111' => ['2021-01-01T0000Z'], # a tried BIRLS ID
# '222' => [], # an untried BIRLS ID
# '333' => [] # an untried BIRLS ID
# }
# NOTE: '111' was not cleared
def add_birls_ids(id_or_ids)
ids = Array.wrap(id_or_ids).map { |id| id.is_a?(Symbol) ? id.to_s : id }
hash = birls_ids_tried_hash
ids.each { |id| hash[id] ||= [] }
self.birls_ids_tried = hash.to_json
self.multiple_birls = true if birls_ids.length > 1
ids
end
def birls_ids
[*birls_ids_tried_hash&.keys, birls_id].compact.uniq
end
def birls_ids_tried_hash
birls_ids_tried.presence&.then { |json| JSON.parse json } || {}
end
def mark_birls_id_as_tried(id = birls_id!, timestamp_string: Time.zone.now.iso8601.to_s)
ids = add_birls_ids id
hash = birls_ids_tried_hash
hash[ids.first] << timestamp_string
self.birls_ids_tried = hash.to_json
timestamp_string
end
def mark_birls_id_as_tried!(*, **)
timestamp_string = mark_birls_id_as_tried(*, **)
save!
timestamp_string
end
def birls_ids_that_havent_been_tried_yet
add_birls_ids birls_id if birls_id.present?
birls_ids_tried_hash.select { |_id, timestamps| timestamps.blank? }.keys
end
def birls_id!
auth_headers[BIRLS_KEY]
end
def birls_id
birls_id! if auth_headers_json
end
def birls_id=(value)
headers = JSON.parse(auth_headers_json) || {}
headers[BIRLS_KEY] = value
self.auth_headers_json = headers.to_json
@auth_headers_hash = nil # reset cache
end
# Called by Sidekiq::Batch as part of the Form 526 submission workflow
# The workflow batch success handler
#
# @param _status [Sidekiq::Batch::Status] the status of the batch
# @param options [Hash] payload set in the workflow batch
#
def perform_ancillary_jobs_handler(_status, options)
submission = Form526Submission.find(options['submission_id'])
# Only run ancillary jobs if submission succeeded
submission.perform_ancillary_jobs(options['first_name']) if submission.jobs_succeeded?
end
def jobs_succeeded?
a_submit_form_526_job_succeeded? && all_other_jobs_succeeded_if_any?
end
def a_submit_form_526_job_succeeded?
submit_form_526_job_statuses = form526_job_statuses.where(job_class: SUBMIT_FORM_526_JOB_CLASSES).order(:updated_at)
submit_form_526_job_statuses.presence&.any?(&:success?)
ensure
successful = submit_form_526_job_statuses.where(status: 'success').load
warn = ->(message) { Rails.logger.warn(message, form_526_submission_id: id) }
warn.call 'There are multiple successful SubmitForm526 job statuses' if successful.size > 1
if successful.size == 1 && submit_form_526_job_statuses.last.unsuccessful?
warn.call "There is a successful SubmitForm526 job, but it's not the most recent SubmitForm526 job"
end
end
def all_other_jobs_succeeded_if_any?
form526_job_statuses.where.not(job_class: SUBMIT_FORM_526_JOB_CLASSES).all?(&:success?)
end
# Creates a batch for the ancillary jobs, sets up the callback, and adds the jobs to the batch if necessary
#
# @param first_name [String] the first name of the user that submitted Form526
# @return [String] the workflow batch id
#
def perform_ancillary_jobs(first_name)
workflow_batch = Sidekiq::Batch.new
workflow_batch.on(
:success,
'Form526Submission#workflow_complete_handler',
'submission_id' => id,
'first_name' => first_name
)
workflow_batch.jobs do
submit_uploads if form[FORM_526_UPLOADS].present?
conditionally_submit_form_4142
submit_form_0781 if form[FORM_0781].present?
submit_form_8940 if form[FORM_8940].present?
upload_bdd_instructions if bdd?
submit_flashes if form[FLASHES].present?
poll_form526_pdf
cleanup
end
end
# Called by Sidekiq::Batch as part of the Form 526 submission workflow
# Checks if all workflow steps were successful and if so marks it as complete.
#
# @param _status [Sidekiq::Batch::Status] the status of the batch
# @param options [Hash] payload set in the workflow batch
#
def workflow_complete_handler(_status, options)
submission = Form526Submission.find(options['submission_id'])
if submission.jobs_succeeded?
# If the received_email_from_polling feature enabled, skip this call
unless Flipper.enabled?(:disability_526_call_received_email_from_polling,
OpenStruct.new({ flipper_id: user_uuid }))
submission.send_received_email('Form526Submission#workflow_complete_handler')
end
submission.workflow_complete = true
submission.save
else
params = submission.personalization_parameters(options['first_name'])
Form526SubmissionFailedEmailJob.perform_async(params)
end
end
def bdd?
form.dig('form526', 'form526', 'bddQualified') || false
end
def personalization_parameters(first_name)
{
'email' => form['form526']['form526']['veteran']['emailAddress'],
# for email templates using VANotify,
# we can conditionally display fields
# by sending an empty string through the payload
'submitted_claim_id' => submitted_claim_id || '',
'date_submitted' => created_at.strftime('%B %-d, %Y %-l:%M %P %Z').sub(/([ap])m/, '\1.m.'),
'date_received' => Time.now.utc.strftime('%B %-d, %Y %-l:%M %P %Z').sub(/([ap])m/, '\1.m.'),
'first_name' => first_name
}
end
def veteran_email_address
form.dig('form526', 'form526', 'veteran', 'emailAddress')
end
def format_creation_time_for_mailers
# We display dates in mailers in the format "May 1, 2024 3:01 p.m. EDT"
created_at.strftime('%B %-d, %Y %-l:%M %P %Z').sub(/([ap])m/, '\1.m.')
end
# Synchronous access to Lighthouse API validation boolean for 526 submission
# Because this method hits an external API, there could be
# exceptions generated for non-200 response codes.
#
# If return is false, then the errors are expected to be
# in the lighthouse_validation_errors Array of Hashes.
#
# NOTE: This is a synchronous access to an external API
# so should not be used within a request/response workflow.
#
def form_content_valid?
transform_service = EVSS::DisabilityCompensationForm::Form526ToLighthouseTransform.new
body = transform_service.transform(form['form526'])
@lighthouse_validation_response = lighthouse_service.validate526(body)
if lighthouse_validation_response&.status == 200
true
else
mock_lighthouse_response(status: lighthouse_validation_response&.status)
false
end
rescue => e
handle_validation_error(e)
false
end
# Returns an Array of Hashes when response.status is 422
# otherwise it's an empty Array.
#
# The Array#empty? is true when there are no errors
# A Hash entry looks like this ...
# {
# "title": "Unprocessable entity",
# "detail": "The property / did not contain the required key serviceInformation",
# "status": "422",
# "source": {
# "pointer": "data/attributes/"
# }
# }
#
def lighthouse_validation_errors
if lighthouse_validation_response&.status == 200
[]
else
lighthouse_validation_response.body['errors']
end
end
def duplicate?
last_remediation&.ignored_as_duplicate?
end
def remediated?
last_remediation&.success || false
end
def failure_type?
!success_type? && !in_process?
end
def success_type?
self.class.success_type.exists?(id:)
end
def in_process?
self.class.in_process.exists?(id:)
end
def last_remediation
form526_submission_remediations&.order(:created_at)&.last
end
def account
return user_account if user_account&.icn.present?
Rails.logger.info('Form526Submission::account - no UserAccount ICN found', log_payload)
# query MPI by EDIPI first & attributes second for user ICN, return in OpenStruct
get_icn_from_mpi
end
# Send the Submitted Email - when the Veteran has clicked the "submit" button in va.gov
# Primary Path: when the response from getting a claim id is successful
# Backup Path: when SubmitForm526 Job has exhausted,
# or when we get a non_retryable_error response from claim establishment flow
# @param invoker: string where the Received Email trigger is being called from
def send_submitted_email(invoker)
if Flipper.enabled?(:disability_526_send_form526_submitted_email)
Rails.logger.info("Form526SubmittedEmailJob called for user #{user_uuid}, submission: #{id} from #{invoker}")
first_name = get_first_name
params = personalization_parameters(first_name)
Form526SubmittedEmailJob.perform_async(params)
end
end
# Send the Received Confirmation Email - when we have confirmed VBMS can start processing the claim
# Primary Path: when the poll for PollForm526PDF job is successful
# Backup Path: when Form526StatusPollingJob reaches "paranoid_success" status
# @param invoker: string where the Received Email trigger is being called from
def send_received_email(invoker)
Rails.logger.info("Form526ConfirmationEmailJob called for user #{user_uuid}, submission: #{id} from #{invoker}")
first_name = get_first_name
params = personalization_parameters(first_name)
Form526ConfirmationEmailJob.perform_async(params)
end
private
def conditionally_submit_form_4142
if Flipper.enabled?(:disability_compensation_production_tester, OpenStruct.new({ flipper_id: user_uuid }))
Rails.logger.info("submit_form_4142 call skipped for submission #{id}")
elsif form[FORM_4142].present?
submit_form_4142
end
end
attr_accessor :lighthouse_validation_response
# Setup the Lighthouse service for this user account.
# Lighthouse calls the user_account.icn the "ID of Veteran"
#
def lighthouse_service
BenefitsClaims::Service.new(account.icn)
end
def handle_validation_error(e)
errors = e.errors if e.respond_to?(:errors)
detail = errors&.dig(0, :detail)
status = errors&.dig(0, :status)
error_msg = "#{detail || e} -- #{e.backtrace[0]}"
mock_lighthouse_response(status:, error: error_msg)
end
def mock_lighthouse_response(status:, error: 'Unknown')
response_struct = Struct.new(:status, :body)
mock_response = response_struct.new(status || 609, nil)
mock_response.body = { 'errors' => [{ 'title' => "Response Status Code '#{mock_response.status}' - #{error}" }] }
@lighthouse_validation_response = mock_response
end
def queue_central_mail_backup_submission_for_non_retryable_error!(e: nil)
# Entry-point for backup 526 CMP submission
#
# Required criteria to send a backup 526 submission from here:
# Enabled in settings and flipper
# Does not have a valid claim ID (through RRD process or otherwise) (protect against dup submissions)
# Does not have a backup submission ID (protect against dup submissions)
backup_job_jid = nil
flipper_sym = :form526_backup_submission_temp_killswitch
send_backup_submission = Settings.form526_backup.enabled &&
Flipper.enabled?(flipper_sym) &&
submitted_claim_id.nil? &&
backup_submitted_claim_id.nil?
backup_job_jid = enqueue_backup_submission(id) if send_backup_submission
log_message = {
submission_id: id
}
log_message['error_class'] = e.class unless e.nil?
log_message['error_message'] = e.message unless e.nil?
log_message['backup_job_id'] = backup_job_jid unless backup_job_jid.nil?
::Rails.logger.error('Form526 Exhausted or Errored (non-retryable-error-path)', log_message)
end
def enqueue_backup_submission(id)
Sidekiq::Form526BackupSubmissionProcess::Submit.perform_async(id)
end
# This method calculates the delay for each upload based on its index in the uploads array.
# The delay is calculated to ensure that uploads are staggered and not sent all at once.
# Duplicate uploads (uploads with the same key) will have an additional delay.
#
# @param upload_index [Integer] the index of the upload in the uploads array
# @param key [String] a unique key for the upload, based on its name and size
# @param uniqueness_tracker [Hash] a hash to track the number of times each unique upload has been seen
# @return [Integer] the total delay in seconds for this upload
#
def calc_submit_delays(upload_index, key, uniqueness_tracker)
delay_per_upload = (upload_index * UPLOAD_DELAY_BASE) # staggered delay based on index
# If the upload is a duplicate, add an additional delay based on how many times it has been seen
dup_delay = [0, (UPLOAD_DELAY_BASE * (uniqueness_tracker[key] - 1 - upload_index))].max
# Final amount to delay
UPLOAD_DELAY_BASE + delay_per_upload + dup_delay
end
def submit_uploads
uploads = form[FORM_526_UPLOADS]
statsd_tags = ["form_id:#{FORM_526}"]
# Send the count of uploads to StatsD, happens before return to capture claims with no uploads
StatsD.gauge('form526.uploads.count', uploads.count, tags: statsd_tags)
return if uploads.blank?
# This happens only when there is 1+ uploads, otherwise will error out
uniq_keys = uploads.map { |upload| "#{upload['name']}_#{upload['size']}" }.uniq
StatsD.gauge('form526.uploads.duplicates', uploads.count - uniq_keys.count, tags: statsd_tags)
uniqueness_tracker = {}
uploads.each_with_index do |upload, upload_index|
key = "#{upload['name']}_#{upload['size']}"
uniqueness_tracker[key] ||= 1
delay = calc_submit_delays(upload_index, key, uniqueness_tracker)
StatsD.gauge('form526.uploads.delay', delay, tags: statsd_tags)
EVSS::DisabilityCompensationForm::SubmitUploads.perform_in(delay, id, upload)
uniqueness_tracker[key] += UNIQUENESS_INCREMENT
end
end
def upload_bdd_instructions
# send BDD instructions
EVSS::DisabilityCompensationForm::UploadBddInstructions.perform_in(60.seconds, id)
end
def submit_form_4142
CentralMail::SubmitForm4142Job.perform_async(id)
end
def submit_form_0781
EVSS::DisabilityCompensationForm::SubmitForm0781.perform_async(id)
end
def submit_form_8940
EVSS::DisabilityCompensationForm::SubmitForm8940.perform_async(id)
end
def submit_flashes
# Note that the User record is cached in Redis -- `User.redis_namespace_ttl`
# If this method runs after the TTL, then the flashes will not be applied -- a possible bug.
BGS::FlashUpdater.perform_async(id) if user && Flipper.enabled?(:disability_compensation_flashes, user)
end
def poll_form526_pdf
# In order to track the status of the 526 PDF upload via Lighthouse,
# call poll_form526_pdf, provided we received a valid claim_id from Lighthouse
if saved_claim.parsed_form['startedFormVersion'].present? && submitted_claim_id
Lighthouse::PollForm526Pdf.perform_async(id)
end
end
def cleanup
EVSS::DisabilityCompensationForm::SubmitForm526Cleanup.perform_async(id)
end
def log_payload
@log_payload ||= { user_uuid:, submission_id: id }
end
def user
@user ||= User.find(user_uuid)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/prescription_preference.rb
|
# frozen_string_literal: true
require 'vets/model'
require 'va_profile/models/email'
##
# Models Prescription notification preference
#
# @!attribute email_address
# @return [String]
# @!attribute rx_flag
# @return [Boolean]
#
class PrescriptionPreference
include Vets::Model
attribute :email_address, String
attribute :rx_flag, Bool
validates :rx_flag, inclusion: { in: [true, false] }
validates(
:email_address,
presence: true,
format: { with: VAProfile::Models::Email::VALID_EMAIL_REGEX },
length: { maximum: 255, minimum: 6 }
)
##
# Build the object for MHV
#
# @raise [Common::Exceptions::ValidationErrors] if invalid attributes
# @return [Hash]
#
def mhv_params
raise Common::Exceptions::ValidationErrors, self unless valid?
{ email_address:, rx_flag: }
end
##
# Compute a hex-formatted digest of the attributes to be used as an ID
#
# @return [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/evss_claims_sync_status_tracker.rb
|
# frozen_string_literal: true
class EVSSClaimsSyncStatusTracker < Common::RedisStore
redis_store REDIS_CONFIG[:evss_claims_store][:namespace]
redis_ttl REDIS_CONFIG[:evss_claims_store][:each_ttl]
redis_key :user_uuid
attribute :user_uuid, String
attribute :status_hash, Hash
attr_accessor :claim_id
def get_collection_status
status_hash[collection_key]
end
def get_single_status
status_hash[single_record_key]
end
def set_collection_status(status)
status_hash[collection_key] = status
save
end
def set_single_status(status)
status_hash[single_record_key] = status
save
end
def delete_collection_status
status_hash.delete(collection_key)
save
end
def delete_single_status
status_hash.delete(single_record_key)
save
end
private
def collection_key
unless user_uuid
raise Common::Exceptions::InternalServerError, ArgumentError.new(
'EVSSClaimsRedisHelper#collection_key was called without having set a user uuid'
)
end
'all'
end
def single_record_key
arr = []
arr << 'claim_id' unless claim_id
arr << 'user_uuid' unless user_uuid
unless arr.empty?
raise Common::Exceptions::InternalServerError, ArgumentError.new(
"EVSSClaimsRedisHelper#single_record_key was called without having set a #{arr.join(', ')}"
)
end
"update_from_remote.#{claim_id}"
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/lighthouse526_document_upload.rb
|
# frozen_string_literal: true
require 'lighthouse/benefits_documents/form526/polled_document_failure_handler'
class Lighthouse526DocumentUpload < ApplicationRecord
include AASM
POLLING_WINDOW = 1.hour
VETERAN_UPLOAD_DOCUMENT_TYPE = 'Veteran Upload'
BDD_INSTRUCTIONS_DOCUMENT_TYPE = 'BDD Instructions'
FORM_0781_DOCUMENT_TYPE = 'Form 0781'
FORM_0781A_DOCUMENT_TYPE = 'Form 0781a'
VALID_DOCUMENT_TYPES = [
BDD_INSTRUCTIONS_DOCUMENT_TYPE,
FORM_0781_DOCUMENT_TYPE,
FORM_0781A_DOCUMENT_TYPE,
VETERAN_UPLOAD_DOCUMENT_TYPE
].freeze
belongs_to :form526_submission
belongs_to :form_attachment, optional: true
validates :lighthouse_document_request_id, presence: true
validates :document_type, presence: true, inclusion: { in: VALID_DOCUMENT_TYPES }
# Veteran Uploads must reference a FormAttachment record, where a Veteran-submitted file is stored
validates :form_attachment, presence: true, if: :veteran_upload?
# Window for polling Lighthouse for the status of an upload
scope :status_update_required, lambda {
where(arel_table[:status_last_polled_at].lt(POLLING_WINDOW.ago.utc))
.or(where(status_last_polled_at: nil))
}
aasm do
state :pending, initial: true
state :completed, :failed
event :complete do
transitions from: :pending, to: :completed, guard: :end_time_saved?
end
event :fail do
transitions from: :pending, to: :failed, guard: %i[end_time_saved? error_message_saved?], after: :handle_failure
end
end
def form0781_types?
[FORM_0781_DOCUMENT_TYPE, FORM_0781A_DOCUMENT_TYPE].include?(document_type)
end
private
def veteran_upload?
document_type == VETERAN_UPLOAD_DOCUMENT_TYPE
end
def end_time_saved?
lighthouse_processing_ended_at != nil
end
def error_message_saved?
error_message != nil
end
def handle_failure
# Do not enable until 100 percent of Lighthouse document upload migration is complete!
if Flipper.enabled?(:disability_compensation_email_veteran_on_polled_lighthouse_doc_failure)
BenefitsDocuments::Form526::PolledDocumentFailureHandler.call(self)
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form_profile.rb
|
# frozen_string_literal: true
require 'string_helpers'
require 'va_profile/configuration'
require 'va_profile/prefill/military_information'
require 'vets/model'
require 'vets/shared_logging'
# TODO(AJD): Virtus POROs for now, will become ActiveRecord when the profile is persisted
class FormFullName
include Vets::Model
attribute :first, String
attribute :middle, String
attribute :last, String
attribute :suffix, String
end
class FormDate
include Vets::Model
attribute :from, Date
attribute :to, Date
end
class FormMilitaryInformation
include Vets::Model
attribute :service_episodes_by_date, VAProfile::Models::ServiceHistory, array: true
attribute :last_service_branch, String
attribute :hca_last_service_branch, String
attribute :last_entry_date, String
attribute :last_discharge_date, String
attribute :discharge_type, String
attribute :post_nov111998_combat, Bool, default: false
attribute :sw_asia_combat, Bool, default: false
attribute :tours_of_duty, Hash, array: true
attribute :currently_active_duty, Bool, default: false
attribute :currently_active_duty_hash, Hash
attribute :vic_verified, Bool, default: false
attribute :service_branches, String, array: true
attribute :service_periods, Hash, array: true
attribute :guard_reserve_service_history, FormDate, array: true
attribute :latest_guard_reserve_service_period, FormDate
end
class FormAddress
include Vets::Model
attribute :street, String
attribute :street2, String
attribute :city, String
attribute :state, String
attribute :country, String
attribute :postal_code, String
end
class FormIdentityInformation
include Vets::Model
attribute :full_name, FormFullName
attribute :date_of_birth, Date
attribute :gender, String
attribute :ssn, String
def hyphenated_ssn
StringHelpers.hyphenated_ssn(ssn)
end
def ssn_last_four
ssn.last(4)
end
end
class FormContactInformation
include Vets::Model
attribute :address, FormAddress
attribute :home_phone, String
attribute :us_phone, String
attribute :mobile_phone, String
attribute :email, String
end
class FormProfile
include Vets::Model
include Vets::SharedLogging
MAPPINGS = Rails.root.glob('config/form_profile_mappings/*.yml').map { |f| File.basename(f, '.*') }
ALL_FORMS = {
acc_rep_management: %w[21-22 21-22A],
adapted_housing: ['26-4555'],
coe: ['26-1880'],
decision_review: %w[20-0995 20-0996 10182],
dependents: %w[686C-674 686C-674-V2],
dependents_verification: %w[21-0538],
dispute_debt: ['DISPUTE-DEBT'],
edu: %w[22-1990 22-1990EMEB 22-1995 22-5490 22-5490E
22-5495 22-0993 22-0994 FEEDBACK-TOOL 22-10203 22-1990EZ
22-10297 22-0803],
evss: ['21-526EZ'],
form_mock_ae_design_patterns: ['FORM-MOCK-AE-DESIGN-PATTERNS'],
form_upload: %w[
21P-4185-UPLOAD
21-651-UPLOAD
21-0304-UPLOAD
21-8960-UPLOAD
21P-4706c-UPLOAD
21-4140-UPLOAD
21P-4718a-UPLOAD
21-4193-UPLOAD
21-0788-UPLOAD
21-8951-2-UPLOAD
21-674b-UPLOAD
21-2680-UPLOAD
21-0779-UPLOAD
21-4192-UPLOAD
21-509-UPLOAD
21-8940-UPLOAD
21P-0516-1-UPLOAD
21P-0517-1-UPLOAD
21P-0518-1-UPLOAD
21P-0519C-1-UPLOAD
21P-0519S-1-UPLOAD
21P-530a-UPLOAD
21P-8049-UPLOAD
],
fsr: ['5655'],
hca: %w[1010ez 10-10EZR],
intent_to_file: ['21-0966'],
ivc_champva: ['10-7959C'],
mdot: ['MDOT'],
memorials: %w[1330M],
pension_burial: %w[21P-0969 21P-530EZ 21P-527EZ 21-2680 21P-601 21P-0537],
vre_counseling: ['28-8832'],
vre_readiness: %w[28-1900 28-1900-V2]
}.freeze
FORM_ID_TO_CLASS = {
'0873' => ::FormProfiles::VA0873,
'10-10EZR' => ::FormProfiles::VA1010ezr,
'10-7959C' => ::FormProfiles::VHA107959c,
'1010EZ' => ::FormProfiles::VA1010ez,
'10182' => ::FormProfiles::VA10182,
'1330M' => ::FormProfiles::VA1330m,
'20-0995' => ::FormProfiles::VA0995,
'20-0996' => ::FormProfiles::VA0996,
'21-0538' => DependentsVerification::FormProfiles::VA210538,
'21-0966' => ::FormProfiles::VA210966,
'21-22' => ::FormProfiles::VA2122,
'21-22A' => ::FormProfiles::VA2122a,
'21-526EZ' => ::FormProfiles::VA526ez,
'21P-0537' => ::FormProfiles::VA21p0537,
'21P-0969' => IncomeAndAssets::FormProfiles::VA21p0969,
'21P-8416' => MedicalExpenseReports::FormProfiles::VA21p8416,
'21P-527EZ' => Pensions::FormProfiles::VA21p527ez,
'21P-530EZ' => Burials::FormProfiles::VA21p530ez,
'21P-601' => ::FormProfiles::VA21p601,
'22-0993' => ::FormProfiles::VA0993,
'22-0994' => ::FormProfiles::VA0994,
'22-0803' => ::FormProfiles::VA0803,
'22-10203' => ::FormProfiles::VA10203,
'22-10297' => ::FormProfiles::VA10297,
'22-1990' => ::FormProfiles::VA1990,
'22-1990EMEB' => ::FormProfiles::VA1990emeb,
'22-1990EZ' => ::FormProfiles::VA1990ez,
'22-1995' => ::FormProfiles::VA1995,
'22-5490' => ::FormProfiles::VA5490,
'22-5490E' => ::FormProfiles::VA5490e,
'22-5495' => ::FormProfiles::VA5495,
'26-1880' => ::FormProfiles::VA261880,
'26-4555' => ::FormProfiles::VA264555,
'28-1900' => ::FormProfiles::VA281900,
'28-1900-V2' => ::FormProfiles::VA281900v2,
'28-8832' => ::FormProfiles::VA288832,
'40-10007' => ::FormProfiles::VA4010007,
'5655' => ::FormProfiles::VA5655,
'686C-674-V2' => ::FormProfiles::VA686c674v2,
'686C-674' => ::FormProfiles::VA686c674,
'21-2680' => ::FormProfiles::VA212680,
'DISPUTE-DEBT' => ::FormProfiles::DisputeDebt,
'FEEDBACK-TOOL' => ::FormProfiles::FeedbackTool,
'FORM-MOCK-AE-DESIGN-PATTERNS' => ::FormProfiles::FormMockAeDesignPatterns,
'MDOT' => ::FormProfiles::MDOT,
'21P-0519S-1-UPLOAD' => ::FormProfiles::FormUpload,
'21-509-UPLOAD' => ::FormProfiles::FormUpload,
'21P-530a-UPLOAD' => ::FormProfiles::FormUpload,
'21-651-UPLOAD' => ::FormProfiles::FormUpload,
'21-674b-UPLOAD' => ::FormProfiles::FormUpload,
'21-0304-UPLOAD' => ::FormProfiles::FormUpload,
'21-0779-UPLOAD' => ::FormProfiles::FormUpload,
'21-0788-UPLOAD' => ::FormProfiles::FormUpload,
'21-2680-UPLOAD' => ::FormProfiles::FormUpload,
'21-4140-UPLOAD' => ::FormProfiles::FormUpload,
'21P-4185-UPLOAD' => ::FormProfiles::FormUpload,
'21-4192-UPLOAD' => ::FormProfiles::FormUpload,
'21-4193-UPLOAD' => ::FormProfiles::FormUpload,
'21P-4706c-UPLOAD' => ::FormProfiles::FormUpload,
'21P-4718a-UPLOAD' => ::FormProfiles::FormUpload,
'21P-8049-UPLOAD' => ::FormProfiles::FormUpload,
'21-8940-UPLOAD' => ::FormProfiles::FormUpload,
'21-8960-UPLOAD' => ::FormProfiles::FormUpload,
'21P-0516-1-UPLOAD' => ::FormProfiles::FormUpload,
'21P-0517-1-UPLOAD' => ::FormProfiles::FormUpload,
'21P-0518-1-UPLOAD' => ::FormProfiles::FormUpload,
'21P-0519C-1-UPLOAD' => ::FormProfiles::FormUpload,
'21-8951-2-UPLOAD' => ::FormProfiles::FormUpload
}.freeze
APT_REGEX = /\S\s+((apt|apartment|unit|ste|suite).+)/i
attr_reader :form_id, :user
attribute :identity_information, FormIdentityInformation
attribute :contact_information, FormContactInformation
attribute :military_information, FormMilitaryInformation
def self.prefill_enabled_forms
forms = %w[40-10007 0873]
ALL_FORMS.each { |type, form_list| forms += form_list if Settings[type].prefill }
forms
end
# lookup FormProfile subclass by form_id and initialize (or use FormProfile if lookup fails)
def self.for(form_id:, user:)
form_id = form_id.upcase
if form_id == '686C-674-V2' && Flipper.enabled?(:dependents_module_enabled, user)
return DependentsBenefits::FormProfiles::VA686c674.new(form_id:, user:)
end
FORM_ID_TO_CLASS.fetch(form_id, self).new(form_id:, user:)
end
def initialize(form_id:, user:)
@form_id = form_id
@user = user
end
def metadata
{}
end
def self.mappings_for_form(form_id)
@mappings ||= {}
@mappings[form_id] || (@mappings[form_id] = load_form_mapping(form_id))
end
def self.load_form_mapping(form_id)
form_id = form_id.downcase if form_id == '1010EZ' # our first form. lessons learned.
file = Rails.root.join('config', 'form_profile_mappings', "#{form_id}.yml")
raise IOError, "Form profile mapping file is missing for form id #{form_id}" unless File.exist?(file)
YAML.load_file(file)
end
# Collects data the VA has on hand for a user. The data may come from many databases/services.
# In case of collisions, preference is given in this order:
# * The form profile cache (the record for this class)
# * ID.me
# * MVI
# * TODO(AJD): MIS (military history)
#
def prefill
@identity_information = initialize_identity_information
@contact_information = initialize_contact_information
@military_information = initialize_military_information
form = form_id == '1010EZ' ? '1010ez' : form_id
if FormProfile.prefill_enabled_forms.include?(form)
mappings = self.class.mappings_for_form(form_id)
form_data = generate_prefill(mappings)
{ form_data:, metadata: }
else
{ metadata: }
end
end
def initialize_military_information
return {} unless user.authorize :va_profile, :access?
military_information_data = {}
military_information_data.merge!(initialize_va_profile_prefill_military_information)
military_information_data[:vic_verified] = user.can_access_id_card?
FormMilitaryInformation.new(military_information_data)
end
private
def initialize_va_profile_prefill_military_information
military_information_data = {}
military_information = VAProfile::Prefill::MilitaryInformation.new(user)
VAProfile::Prefill::MilitaryInformation::PREFILL_METHODS.each do |attr|
military_information_data[attr] = military_information.public_send(attr)
end
military_information_data
rescue => e
log_exception_to_rails(e)
{}
end
def initialize_identity_information
FormIdentityInformation.new(
full_name: user.full_name_normalized,
date_of_birth: user.birth_date,
gender: user.gender,
ssn: user.ssn_normalized
)
end
def vet360_mailing_address_hash
address = vet360_mailing_address
{
street: address.address_line1,
street2: address.address_line2,
city: address.city,
state: address.state_code || address.province,
country: address.country_code_iso3,
postal_code: address.zip_plus_four || address.international_postal_code,
zip_code: address.zip_code
}.compact
end
def vets360_contact_info_hash
return_val = {}
return_val[:email] = vet360_contact_info&.email&.email_address
return_val[:address] = vet360_mailing_address_hash if vet360_mailing_address.present?
phone = vet360_contact_info&.home_phone&.formatted_phone
return_val[:us_phone] = phone
return_val[:home_phone] = phone
return_val[:mobile_phone] = vet360_contact_info&.mobile_phone&.formatted_phone
return_val
end
def initialize_contact_information
opt = {}
opt.merge!(vets360_contact_info_hash) if vet360_contact_info
opt[:address] ||= user_address_hash
format_for_schema_compatibility(opt)
FormContactInformation.new(opt)
end
# doing this (below) instead of `@vet360_contact_info ||= Settings...` to cache nil too
def vet360_contact_info
return @vet360_contact_info if @vet360_contact_info_retrieved
@vet360_contact_info_retrieved = true
if user.icn.present? || user.vet360_id.present?
@vet360_contact_info = VAProfileRedis::V2::ContactInformation.for_user(user)
else
Rails.logger.info('Vet360 Contact Info Null')
end
@vet360_contact_info
end
def vet360_mailing_address
vet360_contact_info&.mailing_address
end
def user_address_hash
{
street: user.address[:street],
street2: user.address[:street2],
city: user.address[:city],
state: user.address[:state],
country: user.address[:country],
postal_code: user.address[:postal_code]
}
end
def format_for_schema_compatibility(opt)
if opt.dig(:address, :street) && opt[:address][:street2].blank? && (apt = opt[:address][:street].match(APT_REGEX))
opt[:address][:street2] = apt[1]
opt[:address][:street] = opt[:address][:street].gsub(/\W?\s+#{apt[1]}/, '').strip
end
%i[home_phone us_phone mobile_phone].each do |phone|
opt[phone] = opt[phone].gsub(/\D/, '') if opt[phone]
end
opt[:address][:postal_code] = opt[:address][:postal_code][0..4] if opt.dig(:address, :postal_code)
end
# returns the veteran's phone number as an object
def phone_object
mobile = vet360_contact_info&.mobile_phone
return mobile if mobile&.area_code && mobile.phone_number
home = vet360_contact_info&.home_phone
return home if home&.area_code && home.phone_number
phone_struct = Struct.new(:area_code, :phone_number)
phone_struct.new
end
def convert_mapping(hash)
prefilled = {}
hash.each do |k, v|
if v.is_a?(Array) && v.any?(Hash)
prefilled[k.camelize(:lower)] = []
v.each do |h|
nested_prefill = {}
h.each do |key, val|
nested_prefill[key.camelize(:lower)] = convert_value(val)
end
prefilled[k.camelize(:lower)] << nested_prefill
end
else
prefilled[k.camelize(:lower)] = convert_value(v)
end
end
prefilled
end
def convert_value(val)
val.is_a?(Hash) ? convert_mapping(val) : call_methods(val)
end
def generate_prefill(mappings)
result = convert_mapping(mappings)
clean!(result)
end
def call_methods(methods)
methods.inject(self) { |a, e| a.send e }.as_json
rescue NoMethodError
nil
end
def clean!(value)
case value
when Hash
clean_hash!(value)
when Array
value.map { |v| clean!(v) }.compact_blank!
else
value
end
end
def clean_hash!(hash)
hash.deep_transform_keys! { |k| k.to_s.camelize(:lower) }
hash.each { |k, v| hash[k] = clean!(v) }
hash.compact_blank!
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/id_card_attributes.rb
|
# frozen_string_literal: true
class IdCardAttributes
attr_accessor :user
def self.for_user(user)
id_attributes = IdCardAttributes.new
id_attributes.user = user
id_attributes
end
# Return dict of traits in canonical order
def traits
{
'edipi' => @user.edipi,
'firstname' => @user.first_name,
'lastname' => @user.last_name,
'address' => @user.address[:street] || '',
'city' => @user.address[:city] || '',
'state' => @user.address[:state] || '',
'zip' => @user.address[:postal_code] || '',
'email' => @user.email || '',
'phone' => @user.home_phone || '',
'title38status' => title38_status_code,
'branchofservice' => branches_of_service,
'dischargetype' => discharge_types
}
end
private
# Mapping from VA Profile branch of service keys to value expected by VIC
SERVICE_KEYS = {
'F' => 'AF', # Air Force
'A' => 'ARMY', # Army
'C' => 'CG', # Coast Guard
'M' => 'MC', # Marine Corps
'N' => 'NAVY', # Navy
'O' => 'NOAA', # NOAA
'H' => 'PHS' # USPHS
}.freeze
def title38_status_code
@user.veteran_status.title38_status || 'UNKNOWN'
rescue
'UNKNOWN'
end
def branches_of_service
branches = military_info.service_episodes_by_date.map do |ep|
SERVICE_KEYS[ep.branch_of_service_code]
end
branches.compact.join(',')
end
def discharge_types
## If the discharge code is one of the known, unwanted three-character
## codes from VA Profile, replace it with nil.
invalid_codes = %w[DVN DVU CVI VNA]
all_codes = military_info.service_episodes_by_date.map(&:character_of_discharge_code)
discharges = all_codes.map { |code| invalid_codes.include?(code) ? nil : code }
# Remove nil values and convert array of codes to a string
discharges.compact.join(',')
end
def military_info
@military_info ||= VAProfile::Prefill::MilitaryInformation.new(user)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form1095_b.rb
|
# frozen_string_literal: true
class Form1095B < ApplicationRecord
has_kms_key
has_encrypted :form_data, key: :kms_key, **lockbox_options
validates :veteran_icn, :tax_year, presence: true
validates :veteran_icn, uniqueness: { scope: :tax_year }
validate :proper_form_data_schema
def txt_file
unless File.exist?(txt_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_file = File.open(txt_template_path, 'r')
rv = template_file.read % data.merge(txt_form_data)
template_file.close
rv
end
def pdf_file
pdftk = PdfForms.new(Settings.binaries.pdftk)
tmp_file = Tempfile.new("1095B-#{SecureRandom.hex}.pdf")
unless File.exist?(pdf_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
generate_pdf(pdftk, tmp_file)
end
# we are currently restricting access to only the most recent tax year
def self.current_tax_year
Date.current.year - 1
end
private
def pdf_template_path
"lib/veteran_enrollment_system/form1095_b/templates/pdfs/1095b-#{tax_year}.pdf"
end
def txt_template_path
"lib/veteran_enrollment_system/form1095_b/templates/txts/1095b-#{tax_year}.txt"
end
def country_and_zip
"#{data[:country]} #{data[:zip_code] || data[:foreign_zip]}"
end
def middle_initial
data[:middle_name] ? data[:middle_name][0] : ''
end
def birthdate_unless_ssn
data[:last_4_ssn].present? ? '' : data[:birth_date]
end
def full_name
[data[:first_name], data[:middle_name].presence, data[:last_name]].compact.join(' ')
end
def name_with_middle_initial
[data[:first_name], middle_initial.presence, data[:last_name]].compact.join(' ')
end
def txt_form_data
text_data = {
birth_date_field: birthdate_unless_ssn,
state_or_province: data[:state] || data[:province],
country_and_zip:,
full_name:,
name_with_middle_initial:,
corrected: data[:is_corrected] ? 'X' : '--'
}
data[:coverage_months].each_with_index do |val, ndx|
field_name = "coverage_month_#{ndx}"
text_data[field_name.to_sym] = val ? 'X' : '--'
end
text_data
end
# rubocop:disable Metrics/MethodLength
def generate_pdf(pdftk, tmp_file)
pdftk.fill_form(
pdf_template_path,
tmp_file,
{
'topmostSubform[0].Page1[0].Pg1Header[0].cb_1[1]': data[:is_corrected] && 2,
'topmostSubform[0].Page1[0].Part1Contents[0].Line1[0].f1_01[0]': data[:first_name],
'topmostSubform[0].Page1[0].Part1Contents[0].Line1[0].f1_02[0]': data[:middle_name],
'topmostSubform[0].Page1[0].Part1Contents[0].Line1[0].f1_03[0]': data[:last_name],
'topmostSubform[0].Page1[0].Part1Contents[0].f1_04[0]': data[:last_4_ssn] || '',
'topmostSubform[0].Page1[0].Part1Contents[0].f1_05[0]': birthdate_unless_ssn,
'topmostSubform[0].Page1[0].Part1Contents[0].f1_06[0]': data[:address],
'topmostSubform[0].Page1[0].Part1Contents[0].f1_07[0]': data[:city],
'topmostSubform[0].Page1[0].Part1Contents[0].f1_08[0]': data[:state] || data[:province],
'topmostSubform[0].Page1[0].Part1Contents[0].f1_09[0]': country_and_zip,
'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]': data[: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]': data[:last_name],
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].f1_28[0]': data[: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]': data[:coverage_months][0] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_02[0]': data[:coverage_months][1] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_03[0]': data[:coverage_months][2] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_04[0]': data[:coverage_months][3] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_05[0]': data[:coverage_months][4] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_06[0]': data[:coverage_months][5] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_07[0]': data[:coverage_months][6] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_08[0]': data[:coverage_months][7] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_09[0]': data[:coverage_months][8] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_10[0]': data[:coverage_months][9] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_11[0]': data[:coverage_months][10] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_12[0]': data[:coverage_months][11] && 1,
'topmostSubform[0].Page1[0].Table1_Part4[0].Row23[0].c1_13[0]': data[:coverage_months][12] && 1
},
flatten: true
)
ret_pdf = tmp_file.read
tmp_file.close
tmp_file.unlink
ret_pdf
rescue PdfForms::PdftkError => e
# in case theres other errors generating the PDF
Rails.logger.error e.message
raise
end
def form_data_schema
{
type: 'object',
required: %w[first_name middle_name last_name address city country coverage_months],
properties: {
first_name: { type: 'string' },
middle_name: { type: 'string' },
last_name: { type: 'string' },
last_4_ssn: {
type: 'string',
pattern: '[0-9]{4}|^$'
},
birth_date: {
type: 'string',
format: 'date'
},
address: { type: 'string' },
city: { type: 'string' },
state: { type: 'string' },
province: { type: 'string' },
country: { type: 'string' },
zip_code: { type: 'string' },
foreign_zip: { type: 'string' },
is_beneficiary: { type: 'boolean' },
is_corrected: { type: 'boolean' },
coverage_months: {
type: 'array',
items: { type: 'boolean' },
minItems: 13,
maxItems: 13
}
}
}
end
# rubocop:enable Metrics/MethodLength
def data
@data ||= JSON.parse(form_data, { symbolize_names: true })
end
def proper_form_data_schema
JSON::Validator.validate!(form_data_schema, form_data)
rescue JSON::Schema::ValidationError => e
errors.add(:form_data, **e)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/gi_bill_feedback.rb
|
# frozen_string_literal: true
class GIBillFeedback < Common::RedisStore
include RedisForm
FORM_ID = 'FEEDBACK-TOOL'
FEEDBACK_MAPPINGS = {
'post9::11 ch 33' => 'Post-9/11 Ch 33',
'chapter33' => 'Post-9/11 Ch 33',
'mGIBAd ch 30' => 'MGIB-AD Ch 30',
'chapter30' => 'MGIB-AD Ch 30',
'mGIBSr ch 1606' => 'MGIB-SR Ch 1606',
'chapter1606' => 'MGIB-SR Ch 1606',
'tatu' => 'TATU',
'reap' => 'REAP',
'dea ch 35' => 'DEA Ch 35',
'chapter35' => 'DEA Ch 35',
'vre ch 31' => 'VRE Ch 31',
'chapter31' => 'VRE Ch 31',
'ta' => 'TA',
'taAgr' => 'TA-AGR',
'myCaa' => 'MyCAA',
'ffa' => 'FFA'
}.freeze
def get_user_details
profile_data = {}
if user.present?
profile_data = {
'active_ICN' => user.icn,
'sec_ID' => user.sec_id
}
end
{ 'profile_data' => profile_data }
end
# rubocop:disable Metrics/MethodLength
def transform_form
transformed = parsed_form.deep_transform_keys(&:underscore)
transformed.delete('privacy_agreement_accepted')
transformed['affiliation'] = transformed.delete('service_affiliation')
transformed.delete('service_date_range').tap do |service_date_range|
next if service_date_range.blank?
transformed['entered_duty'] = service_date_range['from']
transformed['release_from_duty'] = service_date_range['to']
end
transformed.merge!(get_user_details)
transformed['education_details'].tap do |education_details|
school = education_details['school']
transformed['facility_code'] = school.delete('facility_code')
transform_school_address(school['address'])
%w[programs assistance].each do |key|
options_hash = fix_options(parsed_form['educationDetails'][key], key)
education_details[key] = transform_keys_into_array(options_hash)
end
end
transformed['issue'] = transform_keys_into_array(transformed['issue'])
transformed['email'] = transformed.delete('anonymous_email') || transformed.delete('applicant_email')
transformed = Common::HashHelpers.deep_compact(transformed)
transformed.delete('profile_data') if transformed['profile_data'].blank?
transformed
end
# rubocop:enable Metrics/MethodLength
private
def fix_options(options_hash, key)
# if user saves form with options, then goes back to the page
# and fills out options again, then the hash will contain both malformed and
# normal option keys
keys_size = options_hash.keys.size
max_size = VetsJsonSchema::SCHEMAS[FORM_ID]['properties'][
'educationDetails'
]['properties'][key]['properties'].size
return remove_malformed_options(options_hash) if keys_size > max_size
transform_malformed_options(options_hash)
end
def remove_malformed_options(options_hash)
options_hash.except(*FEEDBACK_MAPPINGS.keys)
end
def transform_malformed_options(options_hash)
return_val = {}
options_hash.each do |k, v|
FEEDBACK_MAPPINGS[k].tap do |new_key|
if new_key.blank?
return_val[k] = v
else
return_val[new_key] = v
end
end
end
return_val
end
def transform_school_address(address)
return if address['street3'].blank?
address['street'] = [address['street'], address['street2']].compact.join(', ')
address['street2'] = address.delete('street3')
end
def anonymous?
parsed_form['onBehalfOf'] == 'Anonymous'
end
def transform_keys_into_array(hash)
return [] if hash.blank?
hash.compact_blank!.keys
end
def create_submission_job
user_uuid = anonymous? ? nil : user&.uuid
GIBillFeedbackSubmissionJob.perform_async(id, form, user_uuid)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/category.rb
|
# frozen_string_literal: true
require 'vets/model'
# Category model
class Category
include Vets::Model
def category_id
0
end
attribute :message_category_type, String, array: true, default: -> { [] }
# Categories are simply an array and have no id.
def <=>(other)
category_id <=> other.category_id
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/prescription.rb
|
# frozen_string_literal: true
require 'vets/model'
##
# Models a Prescription
#
# @see https://github.com/department-of-veterans-affairs/vets.gov-team/blob/master/Products/Rx%20Refills/API/sample_mvh_api_calls
#
# @!attribute prescription_id
# @return [Integer]
# @!attribute refill_status
# @return [String]
# @!attribute refill_submit_date
# @return [Vets::Type::UTCTime]
# @!attribute refill_date
# @return [Vets::Type::UTCTime]
# @!attribute refill_remaining
# @return [Integer]
# @!attribute facility_name
# @return [String]
# @!attribute ordered_date
# @return [Vets::Type::UTCTime]
# @!attribute quantity
# @return [String]
# @!attribute expiration_date
# @return [Vets::Type::UTCTime]
# @!attribute prescription_number
# @return [String]
# @!attribute prescription_name
# @return [String]
# @!attribute dispensed_date
# @return [Vets::Type::UTCTime]
# @!attribute station_number
# @return [String]
# @!attribute is_refillable
# @return [Bool]
# @!attribute is_trackable
# @return [Bool]
# @!attribute metadata
# @return [Hash]
#
class Prescription
include Vets::Model
attribute :prescription_id, Integer, filterable: %w[eq not_eq]
attribute :prescription_image, String
attribute :refill_status, String, filterable: %w[eq not_eq]
attribute :refill_submit_date, Vets::Type::UTCTime, filterable: %w[eq not_eq]
attribute :refill_date, Vets::Type::UTCTime
attribute :refill_remaining, Integer
attribute :facility_name, String, filterable: %w[eq not_eq]
attribute :facility_api_name, String
attribute :ordered_date, Vets::Type::UTCTime
attribute :quantity, String
attribute :expiration_date, Vets::Type::UTCTime, filterable: %w[eq lteq gteq]
attribute :prescription_number, String
attribute :sig, String
attribute :prescription_name, String
attribute :dispensed_date, Vets::Type::UTCTime
attribute :station_number, String
attribute :is_refillable, Bool, filterable: %w[eq not_eq]
attribute :is_trackable, Bool, filterable: %w[eq not_eq]
attribute :cmop_division_phone, String
attribute :metadata, Hash, default: -> { {} }
default_sort_by prescription_name: :asc
alias refillable? is_refillable
alias trackable? is_trackable
def <=>(other)
prescription_id <=> other.prescription_id
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/event_bus_gateway_notification.rb
|
# frozen_string_literal: true
class EventBusGatewayNotification < ApplicationRecord
belongs_to :user_account, optional: true
validates :va_notify_id, presence: true
validates :template_id, presence: true
validates :attempts, numericality: { only_integer: true, greater_than_or_equal_to: 1 }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/appeal_submission_upload.rb
|
# frozen_string_literal: true
class AppealSubmissionUpload < ApplicationRecord
validates :decision_review_evidence_attachment_guid, presence: true
belongs_to :appeal_submission
has_one :decision_review_evidence_attachment,
primary_key: 'decision_review_evidence_attachment_guid',
foreign_key: 'guid',
class_name: 'DecisionReviewEvidenceAttachment',
inverse_of: :appeal_submission_upload, dependent: :nullify
scope :failure_not_sent, -> { where(failure_notification_sent_at: nil).order(id: :asc) }
# Matches all characters except first 3 characters, last 6 characters (2 + .pdf extension), underscores, and hyphens
MASK_REGEX = /(?<=.{3})[^_-](?=.{6})/
def masked_attachment_filename
filename = JSON.parse(decision_review_evidence_attachment&.file_data || '{}')['filename']
raise 'Filename for AppealSubmissionUpload not found' if filename.nil?
filename.gsub(MASK_REGEX, 'X')
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user_action.rb
|
# frozen_string_literal: true
class UserAction < ApplicationRecord
belongs_to :acting_user_verification, class_name: 'UserVerification', optional: true
belongs_to :subject_user_verification, class_name: 'UserVerification'
belongs_to :user_action_event
enum :status, { initial: 'initial', success: 'success', error: 'error' }, validate: true
default_scope { order(created_at: :desc) }
def self.ransackable_attributes(_auth_object = nil)
%w[status user_action_event created_at]
end
def self.ransackable_associations(_auth_object = nil)
%w[user_action_event]
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/hca_attachment.rb
|
# frozen_string_literal: true
class HCAAttachment < FormAttachment
ATTACHMENT_UPLOADER_CLASS = HCAAttachmentUploader
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/debt_transaction_log.rb
|
# frozen_string_literal: true
class DebtTransactionLog < ApplicationRecord
belongs_to :transactionable, polymorphic: true
enum :state, pending: 'pending', submitted: 'submitted', completed: 'completed', failed: 'failed'
# Override polymorphic lookup for DigitalDisputeSubmission which stores guid (not id)
# in transactionable_id to avoid exposing sequential IDs externally
def transactionable
if transactionable_type == 'DebtsApi::V0::DigitalDisputeSubmission'
return DebtsApi::V0::DigitalDisputeSubmission.find_by(guid: transactionable_id)
end
super
end
validates :transaction_type, presence: true, inclusion: { in: %w[dispute payment waiver] }
validates :user_uuid, presence: true
validates :debt_identifiers, presence: true
validates :transaction_started_at, presence: true
validates :state, presence: true
def self.track_dispute(submission, user)
DebtTransactionLogService.track_dispute(submission, user)
end
def self.track_waiver(submission, user)
DebtTransactionLogService.track_waiver(submission, user)
end
def mark_submitted(external_reference_id: nil)
DebtTransactionLogService.mark_submitted(transaction_log: self, external_reference_id:)
end
def mark_completed(external_reference_id: nil)
DebtTransactionLogService.mark_completed(transaction_log: self, external_reference_id:)
end
def mark_failed(external_reference_id: nil)
DebtTransactionLogService.mark_failed(transaction_log: self, external_reference_id:)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/maintenance_window.rb
|
# frozen_string_literal: true
class MaintenanceWindow < ApplicationRecord
scope :end_after, ->(time) { where('end_time > ?', time) }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/saved_claim.rb
|
# frozen_string_literal: true
require 'pdf_fill/filler'
# Base class to hold common functionality for Claim submissions.
# Subclasses need to several constants and methods defined:
# * `FORM` should align with the identifier of the form as found in
# the vets-json-schema struct so that validations can be run on submit
# * `CONFIRMATION` should be a small ident used as part of the confirmation
# number to quickly determine the form/product type
# * `regional_office()`, which returns an array or string of the location of
# the claim processing facility
# * `attachment_keys()` returns a list of symbols corresponding to the keys
# in the JSON submission of file upload references. These are iterated over
# in the `process_attachments!` method to associate the previously unmoored
# files to the submitted claim, and to begin processing them.
class SavedClaim < ApplicationRecord
include SetGuid
validates(:form, presence: true)
validate(:form_matches_schema)
validate(:form_must_be_string)
has_kms_key
has_encrypted :form, key: :kms_key, **lockbox_options
has_many :persistent_attachments, inverse_of: :saved_claim, dependent: :destroy
has_many :claim_va_notifications, dependent: :destroy
has_many :form_submissions, dependent: :nullify
has_many :bpds_submissions, class_name: 'BPDS::Submission', dependent: :nullify
has_many :lighthouse_submissions, class_name: 'Lighthouse::Submission', dependent: :nullify
has_many :claims_evidence_api_submissions, class_name: 'ClaimsEvidenceApi::Submission', dependent: :nullify
has_many :parent_of_groups, class_name: 'SavedClaimGroup', foreign_key: 'parent_claim_id',
dependent: :destroy, inverse_of: :parent
has_many :child_of_groups, class_name: 'SavedClaimGroup',
dependent: :destroy, inverse_of: :child
belongs_to :user_account, optional: true
after_create :after_create_metrics
after_destroy :after_destroy_metrics
# create a uuid for this second (used in the confirmation number) and store
# the form type based on the constant found in the subclass.
after_initialize do
self.form_id = self.class::FORM.upcase unless [SavedClaim::DependencyClaim].any? { |k| instance_of?(k) }
end
def self.add_form_and_validation(form_id)
const_set('FORM', form_id)
validates(:form_id, inclusion: [form_id])
end
# Run after a claim is saved, this processes any files and workflows that are present
# and sends them to our internal partners for processing.
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.perform_async(id)
end
def confirmation_number
guid
end
# Convert the json into an OStruct
def open_struct_form
@application ||= JSON.parse(form, object_class: OpenStruct)
end
def parsed_form
@parsed_form ||= JSON.parse(form)
end
def submitted_at
created_at
end
def form_is_string
form.is_a?(String)
end
def form_must_be_string
errors.add(:form, :invalid_format, message: 'must be a json string') unless form_is_string
end
def form_schema
VetsJsonSchema::SCHEMAS[self.class::FORM]
end
def form_matches_schema
return unless form_is_string
schema = form_schema || VetsJsonSchema::SCHEMAS[self.class::FORM]
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(file_name = nil)
PdfFill::Filler.fill_form(self, file_name)
end
def update_form(key, value)
application = parsed_form
application[key] = value
self.form = JSON.generate(application)
end
def business_line
''
end
# the VBMS document type for _this_ claim type
# @see modules/claims_evidence_api/documentation/doctypes.json
def document_type
10 # Unknown
end
# alias for document_type
# using `alias_method` causes 'doctype' to always return 10
def doctype
document_type
end
def email
nil
end
# insert notification after VANotify email send
#
# @see ClaimVANotification
def insert_notification(email_template_id)
claim_va_notifications.create!(
form_type: form_id,
email_sent: true,
email_template_id:
)
end
# Find notification by args*
#
# @param email_template_id
# @see ClaimVANotification
def va_notification?(email_template_id)
claim_va_notifications.find_by(
form_type: form_id,
email_template_id:
)
end
def regional_office
[]
end
# Required for Lighthouse Benefits Intake API submission
# Subclasses can override to provide alternate metadata if needed
def metadata_for_benefits_intake
address = parsed_form['claimantAddress'] || parsed_form['veteranAddress'] || {}
{ veteranFirstName: parsed_form.dig('veteranFullName', 'first'),
veteranLastName: parsed_form.dig('veteranFullName', 'last'),
fileNumber: parsed_form['vaFileNumber'] || parsed_form['veteranSocialSecurityNumber'],
zipCode: address['postalCode'],
businessLine: business_line }
end
private
def validate_schema(schema)
errors = JSONSchemer.validate_schema(schema).to_a
return [] if errors.empty?
reformatted_schemer_errors(errors)
end
def validate_form(schema)
errors = JSONSchemer.schema(schema).validate(parsed_form).to_a
return [] if errors.empty?
reformatted_schemer_errors(errors)
end
# This method exists to change the json_schemer errors
# to be formatted like json_schema errors, which keeps
# the error logging smooth and identical for both options.
# This method also filters out the `data` key because it could
# potentially contain pii.
def reformatted_schemer_errors(errors)
errors.map do |error|
symbolized = error.symbolize_keys
{
data_pointer: symbolized[:data_pointer],
error: symbolized[:error],
details: symbolized[:details],
schema: symbolized[:schema],
root_schema: symbolized[:root_schema],
message: symbolized[:error],
fragment: symbolized[:data_pointer]
}
end
end
def attachment_keys
[]
end
def after_create_metrics
tags = ["form_id:#{form_id}", "doctype:#{document_type}"]
StatsD.increment('saved_claim.create', tags:)
if form_start_date
claim_duration = created_at - form_start_date
StatsD.measure('saved_claim.time-to-file', claim_duration, tags:)
end
pdf_overflow_tracking if Flipper.enabled?(:saved_claim_pdf_overflow_tracking)
end
def after_destroy_metrics
tags = ["form_id:#{form_id}", "doctype:#{document_type}"]
StatsD.increment('saved_claim.destroy', tags:)
end
def pdf_overflow_tracking
tags = ["form_id:#{form_id}", "doctype:#{document_type}"]
form_class = PdfFill::Filler::FORM_CLASSES[form_id]
unless form_class
return Rails.logger.info("#{self.class} Skipping tracking PDF overflow", form_id:, saved_claim_id: id)
end
filename = to_pdf
# @see PdfFill::Filler
# https://github.com/department-of-veterans-affairs/vets-api/blob/96510bd1d17b9e5c95fb6c09d74e53f66b0a25be/lib/pdf_fill/filler.rb#L88
StatsD.increment('saved_claim.pdf.overflow', tags:) if filename.end_with?('_final.pdf')
rescue => e
Rails.logger.warn("#{self.class} Error tracking PDF overflow", form_id:, saved_claim_id: id, error: e)
ensure
Common::FileHelpers.delete_file_if_exists(filename)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/saml_request_tracker.rb
|
# frozen_string_literal: true
require 'common/models/redis_store'
# Temporarily store SAML request details, so that on a return SAML response
# we can lookup associated information.
#
# For example, one use case would be for users logging in via SSOe that need
# to be redirected back to an external application after authentication, rather
# than the VA.gov home page. When a authentication request comes in, with the
# necessary parameter, we can use this Redis namespace to temporarily store a
# redirect url value so that when a matching SAML response comes back from SSOe
# we know where to redirect the newly authenticated user.
class SAMLRequestTracker < Common::RedisStore
redis_store REDIS_CONFIG[:saml_request_tracker][:namespace]
redis_ttl REDIS_CONFIG[:saml_request_tracker][:each_ttl]
redis_key :uuid
attribute :uuid
attribute :payload
attribute :created_at
validates :uuid, presence: true
# Calculate the number of seconds that have elapsed since creation
def age
@created_at ? Time.new.to_i - @created_at : 0
end
def payload_attr(attr)
@payload&.try(:[], attr)
end
def save
@payload ||= {}
@created_at ||= Time.new.to_i
super
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/tracking.rb
|
# frozen_string_literal: true
require 'vets/model'
# Tracking Model
class Tracking
include Vets::Model
attribute :prescription_id, Integer
attribute :prescription_name, String
attribute :prescription_number, String
attribute :facility_name, String
attribute :rx_info_phone_number, String
attribute :ndc_number, String
attribute :shipped_date, Vets::Type::UTCTime
attribute :delivery_service, String
attribute :tracking_number, String
attribute :other_prescriptions, Hash, array: true
default_sort_by shipped_date: :desc
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/central_mail_claim.rb
|
# frozen_string_literal: true
class CentralMailClaim < SavedClaim
has_one(:central_mail_submission, inverse_of: :central_mail_claim, foreign_key: 'saved_claim_id', dependent: :destroy)
before_create(:build_central_mail_submission)
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/intent_to_file_queue_exhaustion.rb
|
# frozen_string_literal: true
class IntentToFileQueueExhaustion < ApplicationRecord
# class used to log and process ITF POST requests that have
# failed to exhaustion. The exact details of what kind of
# processing that will be done for retry attempts will be
# specified in the future.
validates :veteran_icn, presence: true
STATUS = {
unprocessed: 'unprocessed'
}.freeze
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form1010_ezr_attachment.rb
|
# frozen_string_literal: true
class Form1010EzrAttachment < FormAttachment
ATTACHMENT_UPLOADER_CLASS = HCAAttachmentUploader
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/nod_notification.rb
|
# frozen_string_literal: true
require 'json_marshal/marshaller'
class NodNotification < ApplicationRecord
serialize :payload, coder: JsonMarshal::Marshaller
has_kms_key
has_encrypted :payload, key: :kms_key, **lockbox_options
validates(:payload, presence: true)
before_save :serialize_payload
private
def serialize_payload
self.payload = payload.to_json unless payload.is_a?(String)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/expiry_scanner.rb
|
# frozen_string_literal: true
require 'common/client/base'
require 'find'
require 'openssl'
require 'date'
# Adding comment to trigger manifest deployment
class ExpiryScanner
REMAINING_DAYS = 60
URGENT_REMAINING_DAYS = 30
API_PATH = 'https://slack.com/api/chat.postMessage'
def self.scan_certs
result = false
messages = ["Vets-Api #{Settings.vsp_environment} - SSL certificate scan result"]
cert_paths = Dir.glob(directories)
cert_paths.each do |cert_path|
if ['.pem', '.crt'].include?(File.extname(cert_path))
message = define_expiry_urgency(cert_path)
if message.present?
messages << message
result = true
end
end
rescue
Rails.logger.debug { "ERROR: Could not parse certificate #{cert_path}" }
end
Faraday.post(API_PATH, request_body(messages.join("\n")), request_headers) if result
end
def self.define_expiry_urgency(cert_path)
now = DateTime.now
cert = OpenSSL::X509::Certificate.new(File.read(cert_path))
expiry = cert.not_after.to_datetime
return nil if expiry > now + REMAINING_DAYS
if now + URGENT_REMAINING_DAYS > expiry
"URGENT: #{cert_path} expires in less than #{URGENT_REMAINING_DAYS} days: #{expiry}"
else
"ATTENTION: #{cert_path} expires in less than #{REMAINING_DAYS} days: #{expiry}"
end
end
def self.request_body(message)
{
text: message,
channel: Settings.expiry_scanner.slack.channel_id
}.to_json
end
def self.request_headers
{
'Content-type' => 'application/json; charset=utf-8',
'Authorization' => "Bearer #{Settings.argocd.slack.api_key}"
}
end
def self.directories
Settings.expiry_scanner.directories
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/prescription_details.rb
|
# frozen_string_literal: true
require 'vets/model'
class PrescriptionDetails < Prescription
attribute :cmop_division_phone, String
attribute :in_cerner_transition, Bool
attribute :not_refillable_display_message, String
attribute :cmop_ndc_number, String
attribute :user_id, Integer
attribute :provider_first_name, String
attribute :provider_last_name, String
attribute :remarks, String
attribute :division_name, String
attribute :modified_date, Vets::Type::UTCTime
attribute :institution_id, String
attribute :dial_cmop_division_phone, String
attribute :disp_status, String, filterable: %w[eq not_eq]
attribute :ndc, String
attribute :reason, String
attribute :prescription_number_index, String
attribute :prescription_source, String
attribute :disclaimer, String
attribute :indication_for_use, String
attribute :indication_for_use_flag, String
attribute :category, String
attribute :tracking_list, Hash, array: true
attribute :rx_rf_records, Hash, array: true
attribute :tracking, Bool
attribute :orderable_item, String
attribute :sorted_dispensed_date, Date
attribute :shape, String
attribute :color, String
attribute :back_imprint, String
attribute :front_imprint, String
attribute :grouped_medications, String, array: true
default_sort_by prescription_name: :asc
def rx_rf_records=(records)
@rx_rf_records =
if records.is_a?(Hash)
records[:rf_record]
else
records&.dig(0, 1)
end
end
def tracking_list=(records)
@tracking_list =
if records.is_a?(Hash)
records[:tracking]
else
records&.dig(0, 1)
end
end
def sorted_dispensed_date
refill_dates = rx_rf_records&.map { |r| r[:dispensed_date]&.to_date }&.compact
last_refill_date = refill_dates&.max
@sorted_dispensed_date = last_refill_date || dispensed_date&.to_date
end
def cmop_ndc_value
rx_rf_records&.pluck(:cmop_ndc_number)&.compact&.first || cmop_ndc_number.presence
end
def pharmacy_phone_number
return cmop_division_phone if cmop_division_phone.present?
return dial_cmop_division_phone if dial_cmop_division_phone.present?
if rx_rf_records.present?
most_recent_record = rx_rf_records.reduce(nil) do |max, item|
next max if item[:dispensed_date].blank?
max.nil? || item[:dispensed_date] > max[:dispensed_date] ? item : max
end
most_recent_record ||= rx_rf_records.max_by { |item| item[:dispensed_date].presence }
cmop_phone = most_recent_record&.dig(:cmop_division_phone)
return cmop_phone if cmop_phone.present?
dial_phone = most_recent_record&.dig(:dial_cmop_division_phone)
return dial_phone if dial_phone.present?
end
nil
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/saved_claim_group.rb
|
# frozen_string_literal: true
require 'json_marshal/marshaller'
# create_table :saved_claim_group do |t|
# t.uuid :claim_group_guid, null: false
# t.integer :parent_claim_id, null: false, comment: 'ID of the saved claim in vets-api'
# t.integer :saved_claim_id, null: false, comment: 'ID of the saved claim in vets-api'
# t.enum :status, enum_type: 'saved_claim_group_status', default: 'pending'
# t.jsonb :user_data_ciphertext, comment: 'encrypted data that can be used to identify the associated user'
# t.text :encrypted_kms_key, comment: 'KMS key used to encrypt the reference data'
# t.boolean :needs_kms_rotation, default: false, null: false
class SavedClaimGroup < ApplicationRecord
serialize :user_data, coder: ::JsonMarshal::Marshaller
has_kms_key
has_encrypted :user_data, key: :kms_key, **lockbox_options
belongs_to :parent, class_name: 'SavedClaim', foreign_key: 'parent_claim_id', inverse_of: :parent_of_groups
belongs_to :child, class_name: 'SavedClaim', foreign_key: 'saved_claim_id', inverse_of: :child_of_groups
scope :by_claim_group_guid, ->(claim_group_guid) { where(claim_group_guid:) }
scope :by_saved_claim_id, ->(saved_claim_id) { where(saved_claim_id:) }
scope :by_parent_id, ->(parent_claim_id) { where(parent_claim_id:) }
scope :by_status, ->(status) { where(status:) }
scope :pending, -> { by_status('pending') }
scope :needs_kms_rotation, -> { where(needs_kms_rotation: true) }
scope :child_claims_for, ->(parent_id) { where(parent_claim_id: parent_id).where.not(saved_claim_id: parent_id) }
after_create { track_event(:create) }
after_destroy { track_event(:destroy) }
# Claim submission statuses
STATUSES = {
PENDING: 'pending', # default - waiting to be processed
ACCEPTED: 'accepted', # submitted to Sidekiq jobs and/or services
FAILURE: 'failure', # submission failed
PROCESSING: 'processing', # reached service, waiting for decision
SUCCESS: 'success' # submission succeeded
}.freeze
def parent
@parent_claim ||= ::SavedClaim.find(parent_claim_id)
end
def child
@child_claim ||= ::SavedClaim.find(saved_claim_id)
end
# return all the child claims associated with this group
def saved_claim_children
child_ids = SavedClaimGroup.where(claim_group_guid:, parent_claim_id:).map(&:saved_claim_id)
SavedClaim.where(id: child_ids)
end
def parent_claim_group_for_child
SavedClaimGroup.find_by(saved_claim_id: parent_claim_id, parent_claim_id:)
end
def children_of_group
SavedClaimGroup.where(parent_claim_id:).where.not(saved_claim_id: parent_claim_id)
end
def completed?
status.in?([STATUSES[:SUCCESS], STATUSES[:FAILURE]])
end
def failed?
status == STATUSES[:FAILURE]
end
def succeeded?
status == STATUSES[:SUCCESS]
end
private
def track_event(action)
StatsD.increment('saved_claim_group', tags: ["form_id:#{parent.form_id}", "action:#{action}"])
parent_claim = "#{parent.form_id} #{parent.id}"
child_claim = "#{child.form_id} #{child.id}"
Rails.logger.info("#{self.class} #{action} for #{parent_claim} child #{child_claim}")
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/event_bus_gateway_push_notification.rb
|
# frozen_string_literal: true
class EventBusGatewayPushNotification < ApplicationRecord
belongs_to :user_account, optional: true
validates :template_id, presence: true
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/message_search.rb
|
# frozen_string_literal: true
require 'vets/model'
# MessageSearch model
class MessageSearch
include Vets::Model
attribute :exact_match, Bool, default: false
attribute :sender, String
attribute :subject, String
attribute :category, String
attribute :recipient, String
attribute :from_date, Vets::Type::DateTimeString
attribute :to_date, Vets::Type::DateTimeString
attribute :message_id, Integer
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/payment_history.rb
|
# frozen_string_literal: true
require 'vets/model'
class PaymentHistory
include Vets::Model
attribute :payments, Hash, array: true
attribute :return_payments, Hash, array: true
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/evidence_submission.rb
|
# frozen_string_literal: true
require 'lighthouse/benefits_documents/constants'
class EvidenceSubmission < ApplicationRecord
belongs_to :user_account
has_kms_key
has_encrypted :template_metadata, key: :kms_key, **lockbox_options
# Internal Upload statuses:
# CREATED: (Internal status) - the evidence submission record is created.
# QUEUED: (Internal status) - the evidence submission record has been given a job id.
# FAILED: the evidence submission record errored in evss_claim_service.rb, evss/document_upload.rb,
# benefits_documents/service.rb, or lighthouse/evidence_submission/document_upload.rb.
# Lighthouse upload statuses:
# IN_PROGRESS: the workflow is currently executing.
# SUCCESS: the workflow has completed all steps successfully.
# FAILED: the workflow could not complete because a step encountered a non-recoverable error.
scope :created, -> { where(upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:CREATED]) }
scope :queued, -> { where(upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:QUEUED]) }
scope :pending, lambda {
where(upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:PENDING]).where.not(request_id: nil)
}
scope :completed, -> { where(upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:SUCCESS]) }
scope :failed, -> { where(upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:FAILED]) }
# used for sending failure notification emails
scope :va_notify_email_queued, lambda {
where(upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:FAILED])
.where.not(va_notify_date: nil)
.where.not(va_notify_id: nil)
}
# used for sending failure notification emails
scope :va_notify_email_not_queued, lambda {
where(upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:FAILED], va_notify_id: nil, va_notify_date: nil)
}
def completed?
upload_status == BenefitsDocuments::Constants::UPLOAD_STATUS[:SUCCESS]
end
def failed?
upload_status == BenefitsDocuments::Constants::UPLOAD_STATUS[:FAILED]
end
def pending?
upload_status == BenefitsDocuments::Constants::UPLOAD_STATUS[:PENDING] && request_id.present?
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form526_submission_remediation.rb
|
# frozen_string_literal: true
class Form526SubmissionRemediation < ApplicationRecord
belongs_to :form526_submission
validates :lifecycle, presence: true, if: :new_or_changed?
validate :validate_context_on_create_update
validate :ensure_success_if_ignored_as_duplicate
before_create :initialize_lifecycle
enum :remediation_type, { manual: 0, ignored_as_duplicate: 1, email_notified: 2 }
STATSD_KEY_PREFIX = 'form526_submission_remediation'
def mark_as_unsuccessful(context)
self.success = false
if add_context_to_lifecycle(context)
save!
log_to_datadog(context)
end
end
private
def initialize_lifecycle
self.lifecycle ||= []
end
def validate_context_on_create_update
errors.add(:base, 'Context required for create/update actions') if lifecycle.empty? || lifecycle.last.blank?
end
def ensure_success_if_ignored_as_duplicate
errors.add(:success, 'must be true if ignored as duplicate') if ignored_as_duplicate? && !success
end
def log_to_datadog(context)
StatsD.increment("#{STATSD_KEY_PREFIX} marked as unsuccessful: #{context}")
end
def add_context_to_lifecycle(context)
if context.is_a?(String) && context.strip.present?
self.lifecycle << "#{Time.current.strftime('%Y-%m-%d %H:%M:%S')} -- #{context}"
true
else
errors.add(:base, 'Context must be a non-empty string')
false
end
end
def new_or_changed?
new_record? || changed?
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/decision_review_evidence_attachment.rb
|
# frozen_string_literal: true
require 'decision_review/utilities/pdf_validation/service'
# Files uploaded as part of a Notice of Disagreement submission that will be sent to Lighthouse upon form submission.
# inherits from ApplicationRecord
class DecisionReviewEvidenceAttachment < FormAttachment
ATTACHMENT_UPLOADER_CLASS = DecisionReviewEvidenceAttachmentUploader
validate :validate_pdf
belongs_to :appeal_submission_upload,
primary_key: 'guid',
foreign_key: 'decision_review_evidence_attachment_guid',
inverse_of: :decision_review_evidence_attachment,
optional: true
def validate_pdf
validation_enabled = Settings.decision_review.pdf_validation.enabled
validation_enabled ? decision_review_pdf_service.validate_pdf_with_lighthouse(get_file) : true
end
private
def decision_review_pdf_service
DecisionReview::PdfValidation::Service.new
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/invalid_letter_address_edipi.rb
|
# frozen_string_literal: true
class InvalidLetterAddressEdipi < ApplicationRecord
validates :edipi, presence: true, uniqueness: true
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form_attachment.rb
|
# frozen_string_literal: true
require 'vets/shared_logging'
class FormAttachment < ApplicationRecord
include SetGuid
include Vets::SharedLogging
has_kms_key
has_encrypted :file_data, key: :kms_key, **lockbox_options
validates(:file_data, :guid, presence: true)
before_destroy { |record| record.get_file.delete }
def set_file_data!(file, file_password = nil)
attachment_uploader = get_attachment_uploader
file = unlock_pdf(file, file_password) if File.extname(file).downcase == '.pdf' && file_password.present?
attachment_uploader.store!(file)
self.file_data = { filename: attachment_uploader.filename }.to_json
rescue CarrierWave::IntegrityError => e
log_exception_to_sentry(e, nil, nil, 'warn')
log_exception_to_rails(e, 'warn')
raise Common::Exceptions::UnprocessableEntity.new(detail: e.message, source: 'FormAttachment.set_file_data')
end
def parsed_file_data
@parsed_file_data ||= JSON.parse(file_data)
end
def get_file
attachment_uploader = get_attachment_uploader
attachment_uploader.retrieve_from_store!(
parsed_file_data['filename']
)
attachment_uploader.file
end
private
def unlock_pdf(file, file_password)
pdftk = PdfForms.new(Settings.binaries.pdftk)
tmpf = Tempfile.new(['decrypted_form_attachment', '.pdf'])
begin
pdftk.call_pdftk(file.tempfile.path, 'input_pw', file_password, 'output', tmpf.path)
rescue PdfForms::PdftkError => e
file_regex = %r{/(?:\w+/)*[\w-]+\.pdf\b}i
password_regex = /(input_pw).*?(output)/
sanitized_message = e.message.gsub(file_regex, '[FILTERED FILENAME]').gsub(password_regex, '\1 [FILTERED] \2')
log_message_to_sentry(sanitized_message, 'warn')
log_message_to_rails(sanitized_message, 'warn')
raise Common::Exceptions::UnprocessableEntity.new(
detail: I18n.t('errors.messages.uploads.pdf.incorrect_password'),
source: 'FormAttachment.unlock_pdf'
)
end
file.tempfile.unlink
file.tempfile = tmpf
file
end
def get_attachment_uploader
@au ||= self.class::ATTACHMENT_UPLOADER_CLASS.new(guid)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/health_facility.rb
|
# frozen_string_literal: true
class HealthFacility < ApplicationRecord
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/rate_limited_search.rb
|
# frozen_string_literal: true
class RateLimitedSearch < Common::RedisStore
COUNT_LIMIT = 3
redis_store(name.underscore)
redis_ttl(86_400)
redis_key(:search_params)
attribute(:count, Integer, default: 1)
attribute(:search_params, String)
class RateLimitedError < Common::Exceptions::TooManyRequests
end
def self.create_or_increment_count(search_params)
hashed_params = Digest::SHA2.hexdigest(search_params)
rate_limited_search = find(hashed_params)
if rate_limited_search
raise RateLimitedError if rate_limited_search.count >= COUNT_LIMIT
rate_limited_search.count += 1
rate_limited_search.save!
else
create(search_params: hashed_params)
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/in_progress_form.rb
|
# frozen_string_literal: true
require 'json_marshal/marshaller'
class InProgressForm < ApplicationRecord
belongs_to :user_account, dependent: nil, optional: false
class CleanUUID < ActiveRecord::Type::String
def cast(value)
super(value.to_s.delete('-'))
end
alias serialize cast
end
attr_accessor :real_user_uuid
RETURN_URL_SQL = "CAST(metadata -> 'returnUrl' AS text)"
attribute :user_uuid, CleanUUID.new
has_kms_key
has_encrypted :form_data, key: :kms_key, **lockbox_options
enum :status, %w[pending processing], prefix: :submission, default: :pending
scope :submission_pending, -> { where(status: [nil, 'pending']) } # override to include nil
scope :has_attempted_submit, lambda {
where("(metadata -> 'submission' ->> 'hasAttemptedSubmit')::boolean or " \
"(metadata -> 'submission' ->> 'has_attempted_submit')::boolean")
}
scope :has_errors, -> { where("(metadata -> 'submission' -> 'errors') IS NOT NULL") }
scope :has_no_errors, -> { where.not("(metadata -> 'submission' -> 'errors') IS NOT NULL") }
scope :has_error_message, lambda {
where("(metadata -> 'submission' -> 'errorMessage')::text !='false' or " \
"(metadata -> 'submission' -> 'error_message')::text !='false' ")
}
# the double quotes in return_url are part of the value
scope :return_url, ->(url) { where(%( #{RETURN_URL_SQL} = ? ), "\"#{url}\"") }
scope :for_form, ->(form_id) { where(form_id:) }
scope :not_submitted, -> { where.not("metadata -> 'submission' ->> 'status' = ?", 'applicationSubmitted') }
scope :unsubmitted_fsr, -> { for_form('5655').not_submitted }
serialize :form_data, coder: JsonMarshal::Marshaller
validates(:form_data, presence: true)
validates(:user_uuid, presence: true)
# https://guides.rubyonrails.org/active_record_callbacks.html
before_save :serialize_form_data
before_create :set_expires_at
after_create ->(ipf) { StatsD.increment('in_progress_form.create', tags: ["form_id:#{ipf.form_id}"]) }
after_destroy ->(ipf) { StatsD.increment('in_progress_form.destroy', tags: ["form_id:#{ipf.form_id}"]) }
after_destroy lambda { |ipf|
StatsD.measure('in_progress_form.lifespan', Time.current - ipf.created_at,
tags: ["form_id:#{ipf.form_id}"])
}
after_save :log_hca_email_diff
def self.form_for_user(form_id, user, with_lock: false)
if Flipper.enabled?(:in_progress_form_atomicity, user)
scope = with_lock ? lock : all
user_uuid_form = scope.find_by(form_id:, user_uuid: user.uuid)
user_account_form = scope.find_by(form_id:, user_account: user.user_account) if user.user_account
else
user_uuid_form = InProgressForm.find_by(form_id:, user_uuid: user.uuid)
user_account_form = InProgressForm.find_by(form_id:, user_account: user.user_account) if user.user_account
end
user_uuid_form || user_account_form
end
def self.for_user(user)
user_uuid_forms = InProgressForm.where(user_uuid: user.uuid)
if user.user_account
user_uuid_forms.or(InProgressForm.where(user_account: user.user_account))
else
user_uuid_forms
end
end
def data_and_metadata
{
formData: JSON.parse(form_data),
metadata:
}
end
def metadata
data = super || {}
last_accessed = updated_at || Time.current
data.merge(
'createdAt' => created_at&.to_time.to_i,
'expiresAt' => expires_at.to_i || (last_accessed + expires_after).to_i,
'lastUpdated' => updated_at.to_i,
'inProgressFormId' => id
)
end
##
# Determines an expiration duration based on the UI form_id.
#
# @return [ActiveSupport::Duration] an instance of ActiveSupport::Duration
#
def expires_after
@expires_after ||= case form_id
when '21-526EZ', '21P-527EZ', '21P-530EZ', '686C-674-V2'
1.year
else
60.days
end
end
def next_expires_at
skippable_forms = %w[21P-527EZ 21-526EZ 5655]
skippable_forms.include?(form_id) ? expires_at : (Time.current + expires_after)
end
private
def set_expires_at
self.expires_at ||= Time.current + expires_after
end
def log_hca_email_diff
HCA::LogEmailDiffJob.perform_async(id, real_user_uuid, user_account_id) if form_id == '1010ez'
end
def serialize_form_data
self.form_data = form_data.to_json unless form_data.is_a?(String)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/iam_session.rb
|
# frozen_string_literal: true
# Subclasses the `Session` model. Adds a unique redis namespace for IAM sessions.
#
class IAMSession < Session
redis_store REDIS_CONFIG[:iam_session][:namespace]
redis_ttl REDIS_CONFIG[:iam_session][:each_ttl]
redis_key :token
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/ivc_champva_form.rb
|
# frozen_string_literal: true
class IvcChampvaForm < ApplicationRecord
validates :form_uuid, presence: true
has_kms_key
has_encrypted :ves_request_data, key: :kms_key, **lockbox_options
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/evss_claim_document.rb
|
# frozen_string_literal: true
require 'vets/model'
require 'pdf_info'
require 'vets/shared_logging'
class EVSSClaimDocument
include Vets::Model
include ActiveModel::Validations::Callbacks
include Vets::SharedLogging
attribute :evss_claim_id, Integer
attribute :tracked_item_id, Integer
attribute :document_type, String
attribute :file_name, String
attribute :uuid, String
attribute :file_obj, ActionDispatch::Http::UploadedFile
attribute :password, String
validates(:file_name, presence: true)
validate :known_document_type?
validate :content_type_matches_extension?
validate :unencrypted_pdf?
before_validation :normalize_text, :convert_to_unlocked_pdf, :normalize_file_name
# rubocop:disable Layout/LineLength
DOCUMENT_TYPES = {
'1489' => 'Hypertension Rapid Ready For Decision Summary PDF',
'L014' => 'Birth Certificate',
'L015' => 'Buddy/Lay Statement',
'L018' => 'Civilian Police Reports',
'L023' => 'Other Correspondence',
'L029' => 'Copy of a DD214',
'L033' => 'Death Certificate',
'L034' => 'Military Personnel Record',
'L037' => 'Divorce Decree',
'L048' => 'Medical Treatment Record - Government Facility',
'L049' => 'Medical Treatment Record - Non-Government Facility',
'L051' => 'Marriage Certificate',
'L070' => 'Photographs',
'L102' => 'VA Form 21-2680 - Examination for Housebound Status or Permanent Need for Regular Aid & Attendance',
'L107' => 'VA Form 21-4142 - Authorization To Disclose Information',
'L115' => 'VA Form 21-4192 - Request for Employment Information in Connection with Claim for Disability',
'L117' => 'VA Form 21-4502 - Application for Automobile or Other Conveyance and Adaptive Equipment Under 38 U.S.C. 3901-3904',
'L133' => 'VA Form 21-674 - Request for Approval of School Attendance',
'L139' => 'VA Form 21-686c - Declaration of Status of Dependents',
'L149' => 'VA Form 21-8940 - Veterans Application for Increased Compensation Based on Un-employability',
'L159' => 'VA Form 26-4555 - Application in Acquiring Specially Adapted Housing or Special Home Adaptation Grant',
'L222' => 'VA Form 21-0779 - Request for Nursing Home Information in Connection with Claim for Aid & Attendance',
'L228' => 'VA Form 21-0781 - Statement in Support of Claimed Mental Health Disorder(s) Due to an In-Service Traumatic Event(s)',
'L229' => 'VA Form 21-0781a - Statement in Support of Claim for PTSD Secondary to Personal Assault',
'L418' => 'Court papers / documents',
'L450' => 'STR - Dental - Photocopy',
'L451' => 'STR - Medical - Photocopy',
'L478' => 'Medical Treatment Records - Furnished by SSA',
'L702' => 'Disability Benefits Questionnaire (DBQ)',
'L703' => 'Goldmann Perimetry Chart/Field Of Vision Chart',
'L827' => 'VA Form 21-4142a - General Release for Medical Provider Information',
'L1489' => 'Automated Review Summary Document'
}.freeze
# rubocop:enable Layout/LineLength
EVSS_TEXT_ENCODING = 'ascii' # EVSS only accepts text files written in ASCII
MINIMUM_ENCODING_CONFIDENCE = 0.5
def description
DOCUMENT_TYPES[document_type]
end
def uploader_ids
[tracked_item_id, uuid]
end
def ==(other)
attributes == other.attributes
end
def to_serializable_hash
# file_obj is not suitable for serialization
attributes.tap { |h| h.delete :file_obj }
end
# The front-end URL encodes a nil tracked_item_id as the string 'null'
def tracked_item_id=(num)
@tracked_item_id = num == 'null' ? nil : num
end
private
def content_type_matches_extension?
return unless file_obj
true_mime_type = MimeMagic.by_magic(File.open(file_obj.tempfile.path)).to_s
# MimeMagic cannot always determine the mime_type and will sometimes
# return ''. In those cases it makes sense to fall back to the content_type
# as passed in when the request is made
true_mime_type = file_obj.content_type if true_mime_type.empty?
assumed_mime_type = MimeMagic.by_extension(extension).to_s
errors.add(:base, I18n.t('errors.messages.uploads.content_type_mismatch')) if true_mime_type != assumed_mime_type
end
def extension
# Using file_name instead of file_path because the temp path doesn't include
# an extension
File.extname(file_name).downcase[1..] # Remove the leading dot
end
def known_document_type?
errors.add(:base, I18n.t('errors.messages.uploads.document_type_unknown')) unless description
end
def convert_to_unlocked_pdf
return unless file_name.match?(/\.pdf$/i) && password.present?
pdftk = PdfForms.new(Settings.binaries.pdftk)
tempfile_without_pass = Tempfile.new(['decrypted_evss_claim_document', '.pdf'])
begin
pdftk.call_pdftk(file_obj.tempfile.path,
'input_pw', password,
'output', tempfile_without_pass.path)
rescue PdfForms::PdftkError => e
file_regex = %r{/(?:\w+/)*[\w-]+\.pdf\b}
password_regex = /(input_pw).*?(output)/
sanitized_message = e.message.gsub(file_regex, '[FILTERED FILENAME]').gsub(password_regex, '\1 [FILTERED] \2')
log_message_to_sentry(sanitized_message, 'warn')
log_message_to_rails(sanitized_message, 'warn')
errors.add(:base, I18n.t('errors.messages.uploads.pdf.incorrect_password'))
end
@password = nil
file_obj.tempfile.unlink
file_obj.tempfile = tempfile_without_pass
end
def unencrypted_pdf?
return unless file_name.match?(/\.pdf$/i) && file_obj
metadata = PdfInfo::Metadata.read(file_obj.tempfile)
errors.add(:base, I18n.t('errors.messages.uploads.encrypted')) if metadata.encrypted?
Rails.logger.info("Document for claim #{evss_claim_id} is encrypted") if metadata.encrypted?
file_obj.tempfile.rewind
rescue PdfInfo::MetadataReadError => e
Rails.logger.info("MetadataReadError: Document for claim #{evss_claim_id}")
log_exception_to_sentry(e, nil, nil, 'warn')
log_exception_to_rails(e)
if e.message.include?('Incorrect password')
errors.add(:base, I18n.t('errors.messages.uploads.pdf.locked'))
else
errors.add(:base, I18n.t('errors.messages.uploads.malformed_pdf'))
end
end
def normalize_text
return unless file_name.match?(/\.txt$/i) && file_obj
text = file_obj.read
text = text.encode(EVSS_TEXT_ENCODING)
file_obj.tempfile = Tempfile.new(encoding: EVSS_TEXT_ENCODING)
file_obj.tempfile.write text
file_obj.tempfile.rewind
rescue Encoding::UndefinedConversionError
errors.add(:base, I18n.t('errors.messages.uploads.ascii_encoded'))
end
def normalize_file_name
return if !file_name || file_name.frozen?
# remove all but the last "." in the file name
file_name.gsub!(/[.](?=.*[.])/, '')
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/evss_claim.rb
|
# frozen_string_literal: true
require 'evss/documents_service'
class EVSSClaim < ApplicationRecord
belongs_to :user_account, dependent: nil, optional: true
def self.for_user(user)
claim_for_user_uuid(user.uuid).or(claim_for_user_account(user.user_account))
end
def self.claim_for_user_uuid(user_uuid)
return EVSSClaim.none unless user_uuid
where(user_uuid:)
end
def self.claim_for_user_account(user_account)
return EVSSClaim.none unless user_account
where(user_account:)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form_submission_attempt.rb
|
# frozen_string_literal: true
require 'logging/call_location'
require 'zero_silent_failures/monitor'
class FormSubmissionAttempt < ApplicationRecord
include AASM
belongs_to :form_submission
has_one :saved_claim, through: :form_submission
has_one :in_progress_form, through: :form_submission
has_one :user_account, through: :form_submission
has_kms_key
has_encrypted :error_message, :response, key: :kms_key, **lockbox_options
# We only have the ignored_columns here because I haven't yet removed the error_message and
# response columns from the db. (The correct column names are error_message_ciphertext and response_ciphertext)
# If we get around to doing that, we shouldn't need the following line.
self.ignored_columns += %w[error_message response]
def self.latest_attempts
select('DISTINCT ON (form_submission_id) form_submission_id, benefits_intake_uuid')
.order('form_submission_id, created_at DESC')
end
aasm do
after_all_transitions :log_status_change
state :pending, initial: true
state :failure, :success, :vbms
state :manually
event :fail do
after do
form_type = form_submission.form_type
claim_id = form_submission&.saved_claim_id
log_info = { form_submission_id:,
claim_id:,
benefits_intake_uuid:,
form_type:,
user_account_uuid: form_submission.user_account_id }
if should_send_simple_forms_email
Rails.logger.info('Preparing to send Form Submission Attempt error email', log_info)
simple_forms_enqueue_result_email
elsif form_type == CentralMail::SubmitForm4142Job::FORM4142_FORMSUBMISSION_TYPE
form526_form4142_email(log_info)
end
end
transitions from: :pending, to: :failure
end
event :succeed do
transitions from: :pending, to: :success
end
event :vbms do
after do
simple_forms_enqueue_result_email if should_send_simple_forms_email
end
transitions from: :pending, to: :vbms
transitions from: :success, to: :vbms
end
event :remediate do
transitions from: :failure, to: :vbms
end
event :manual do
transitions from: :failure, to: :manually
end
end
def log_status_change
log_level = :info
log_hash = status_change_hash
case aasm.current_event
when :fail!
log_level = :error
log_hash[:message] = 'Form Submission Attempt failed'
when :manual!
log_level = :warn
log_hash[:message] = 'Form Submission Attempt is being manually remediated'
when :vbms!
log_hash[:message] = 'Form Submission Attempt went to vbms'
else
log_hash[:message] = 'Form Submission Attempt State change'
end
Rails.logger.public_send(log_level, log_hash)
end
private
def status_change_hash
{
form_submission_id:,
benefits_intake_uuid:,
form_type: form_submission&.form_type,
claim_id: form_submission&.saved_claim_id,
from_state: aasm.from_state,
to_state: aasm.to_state,
event: aasm.current_event
}
end
def queue_form526_form4142_email(form526_submission_id, log_info)
Rails.logger.info('Queuing Form526:Form4142 failure email to VaNotify',
log_info.merge({ form526_submission_id: }))
jid = EVSS::DisabilityCompensationForm::Form4142DocumentUploadFailureEmail.perform_async(
form526_submission_id
)
Rails.logger.info('Queuing Form526:Form4142 failure email to VaNotify completed',
log_info.merge({ jid:, form526_submission_id: }))
end
def form526_form4142_email(log_info)
if Flipper.enabled?(CentralMail::SubmitForm4142Job::POLLED_FAILURE_EMAIL)
queue_form526_form4142_email(Form526Submission.find_by(saved_claim_id:).id, log_info)
else
Rails.logger.info(
'Would queue EVSS::DisabilityCompensationForm::Form4142DocumentUploadFailureEmail, but flipper is off.',
log_info.merge({ form526_submission_id: })
)
end
rescue => e
cl = caller_locations.first
call_location = Logging::CallLocation.new(
CentralMail::SubmitForm4142Job::ZSF_DD_TAG_FUNCTION, cl.path, cl.lineno
)
ZeroSilentFailures::Monitor.new(Form526Submission::ZSF_DD_TAG_SERVICE).log_silent_failure(
log_info.merge({ error_class: e.class, error_message: e.message }),
log_info[:user_account_uuid], call_location:
)
end
def should_send_simple_forms_email
simple_forms_form_number && Flipper.enabled?(:simple_forms_email_notifications)
end
def simple_forms_enqueue_result_email
form_number = simple_forms_form_number
Rails.logger.info('Queuing SimpleFormsAPI notification email to VaNotify', form_number:, benefits_intake_uuid:)
jid = SimpleFormsApi::Notification::SendNotificationEmailJob.perform_async(benefits_intake_uuid, form_number)
Rails.logger.info(
'Queuing SimpleFormsAPI notification email to VaNotify completed',
jid:,
form_number:,
benefits_intake_uuid:
)
end
def simple_forms_form_number
@simple_forms_form_number ||=
if (
SimpleFormsApi::Notification::Email::TEMPLATE_IDS.keys +
SimpleFormsApi::Notification::FormUploadEmail::SUPPORTED_FORMS
).include? form_submission.form_type
form_submission.form_type
else
SimpleFormsApi::V1::UploadsController::FORM_NUMBER_MAP[form_submission.form_type]
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form526_job_status.rb
|
# frozen_string_literal: true
class Form526JobStatus < ApplicationRecord
belongs_to :form526_submission
alias submission form526_submission
FAILURE_STATUSES = {
non_retryable_error: 'non_retryable_error',
exhausted: 'exhausted'
}.freeze
SUCCESS_STATUSES = {
success: 'success',
pdf_found_later: 'pdf_found_later', # manually applied by dev when PDF is found after initial failure
pdf_success_on_backup_path: 'pdf_success_on_backup_path', # manually applied by dev when PDF created via backup path
pdf_manually_uploaded: 'pdf_manually_uploaded' # manually applied by dev when PDF is uploaded manually
}.freeze
STATUS = {
try: 'try',
success: 'success',
retryable_error: 'retryable_error',
pdf_not_found: 'pdf_not_found',
pdf_found_later: 'pdf_found_later',
pdf_success_on_backup_path: 'pdf_success_on_backup_path',
pdf_manually_uploaded: 'pdf_manually_uploaded'
}.merge(FAILURE_STATUSES).freeze
store_accessor :bgjob_errors
def success?
SUCCESS_STATUSES.values.include?(status)
end
def unsuccessful?
!success?
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/decision_review_notification_audit_log.rb
|
# frozen_string_literal: true
require 'json_marshal/marshaller'
class DecisionReviewNotificationAuditLog < ApplicationRecord
serialize :payload, coder: JsonMarshal::Marshaller
has_kms_key
has_encrypted :payload, key: :kms_key, **lockbox_options
validates(:payload, presence: true)
before_save :serialize_payload
private
def serialize_payload
self.payload = payload.to_json unless payload.is_a?(String)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/lighthouse_document.rb
|
# frozen_string_literal: true
require 'vets/model'
require 'pdf_info'
require 'common/pdf_helpers'
class LighthouseDocument
include Vets::Model
include ActiveModel::Validations::Callbacks
include Vets::SharedLogging
attribute :first_name, String
attribute :claim_id, Integer
attribute :document_type, String
attribute :file_name, String
attribute :file_extension, String
attribute :file_obj, ActionDispatch::Http::UploadedFile
attribute :participant_id, String
attribute :password, String
attribute :tracked_item_id, Integer
attribute :uuid, String
validates(:file_name, presence: true)
validates(:participant_id, presence: true)
validate :known_document_type?
validate :unencrypted_pdf?
# Taken from LighthouseDocumentUploaderBase
validates(:file_extension, inclusion: { in: %w[pdf gif png tiff tif jpeg jpg bmp txt] })
before_validation :set_file_extension, :normalize_text, :convert_to_unlocked_pdf, :normalize_file_name
# rubocop:disable Layout/LineLength
DOCUMENT_TYPES = {
'1489' => 'Hypertension Rapid Ready For Decision Summary PDF',
'L014' => 'Birth Certificate',
'L015' => 'Buddy/Lay Statement',
'L018' => 'Civilian Police Reports',
'L023' => 'Other Correspondence',
'L029' => 'Copy of a DD214',
'L033' => 'Death Certificate',
'L034' => 'Military Personnel Record',
'L037' => 'Divorce Decree',
'L048' => 'Medical Treatment Record - Government Facility',
'L049' => 'Medical Treatment Record - Non-Government Facility',
'L051' => 'Marriage Certificate',
'L070' => 'Photographs',
'L102' => 'VA Form 21-2680 - Examination for Housebound Status or Permanent Need for Regular Aid & Attendance',
'L107' => 'VA Form 21-4142 - Authorization To Disclose Information',
'L115' => 'VA Form 21-4192 - Request for Employment Information in Connection with Claim for Disability',
'L117' => 'VA Form 21-4502 - Application for Automobile or Other Conveyance and Adaptive Equipment Under 38 U.S.C. 3901-3904',
'L133' => 'VA Form 21-674 - Request for Approval of School Attendance',
'L139' => 'VA Form 21-686c - Declaration of Status of Dependents',
'L149' => 'VA Form 21-8940 - Veterans Application for Increased Compensation Based on Un-employability',
'L159' => 'VA Form 26-4555 - Application in Acquiring Specially Adapted Housing or Special Home Adaptation Grant',
'L222' => 'VA Form 21-0779 - Request for Nursing Home Information in Connection with Claim for Aid & Attendance',
'L228' => 'VA Form 21-0781 - Statement in Support of Claimed Mental Health Disorder(s) Due to an In-Service Traumatic Event(s)',
'L229' => 'VA Form 21-0781a - Statement in Support of Claim for PTSD Secondary to Personal Assault',
'L418' => 'Court papers / documents',
'L450' => 'STR - Dental - Photocopy',
'L451' => 'STR - Medical - Photocopy',
'L478' => 'Medical Treatment Records - Furnished by SSA',
'L702' => 'Disability Benefits Questionnaire (DBQ)',
'L703' => 'Goldmann Perimetry Chart/Field Of Vision Chart',
'L827' => 'VA Form 21-4142a - General Release for Medical Provider Information',
'L1489' => 'Automated Review Summary Document'
}.freeze
# rubocop:enable Layout/LineLength
LIGHTHOUSE_TEXT_ENCODING = 'ascii' # Lighthouse only accepts text files written in ASCII
MINIMUM_ENCODING_CONFIDENCE = 0.5
def description
DOCUMENT_TYPES[document_type]
end
def uploader_ids
[tracked_item_id, uuid]
end
def ==(other)
attributes == other.attributes
end
def to_serializable_hash
# file_obj is not suitable for serialization
attributes.tap { |h| h.delete :file_obj }
end
# The front-end URL encodes a nil tracked_item_id as the string 'null'
def tracked_item_id=(num)
@tracked_item_id = num == 'null' ? nil : num
end
private
def known_document_type?
errors.add(:base, I18n.t('errors.messages.uploads.document_type_unknown')) unless description
end
def convert_to_unlocked_pdf
return unless file_name.match?(/\.pdf$/i) && password.present?
tempfile_without_pass = Tempfile.new(%w[decrypted_lighthouse_claim_document .pdf])
unlock_succeeded = false
begin
# Choose PDF unlocking strategy
if Flipper.enabled?(:lighthouse_document_convert_to_unlocked_pdf_use_hexapdf)
unlock_with_hexapdf(tempfile_without_pass)
else
unlock_with_pdftk(tempfile_without_pass)
end
unlock_succeeded = true
# Only swap files if unlock succeeded
file_obj.tempfile.unlink
file_obj.tempfile = tempfile_without_pass
ensure
cleanup_after_unlock(tempfile_without_pass, unlock_succeeded)
end
end
def unlock_with_hexapdf(tempfile_without_pass)
::Common::PdfHelpers.unlock_pdf(file_obj.tempfile.path, password, tempfile_without_pass)
tempfile_without_pass.rewind
rescue Common::Exceptions::UnprocessableEntity => e
log_pdf_unlock_error(e)
errors.add(:base, I18n.t('errors.messages.uploads.pdf.incorrect_password'))
end
def unlock_with_pdftk(tempfile_without_pass)
pdftk = PdfForms.new(Settings.binaries.pdftk)
begin
pdftk.call_pdftk(file_obj.tempfile.path,
'input_pw', password,
'output', tempfile_without_pass.path)
rescue PdfForms::PdftkError => e
handle_pdftk_error(e)
end
end
def handle_pdftk_error(error)
log_pdf_unlock_error(error)
errors.add(:base, I18n.t('errors.messages.uploads.pdf.incorrect_password'))
end
def log_pdf_unlock_error(error)
file_regex = %r{/(?:\w+/)*[\w-]+\.pdf\b}
password_regex = /(input_pw).*?(output)/
is_va_gov_service_error = error.respond_to?(:errors)
message = is_va_gov_service_error ? error.errors&.first&.detail : error.message
sanitized_message = message.gsub(file_regex, '[FILTERED FILENAME]')
.gsub(password_regex, '\1 [FILTERED] \2')
error_source = is_va_gov_service_error ? error.errors&.first&.source : 'pdftk'
sanitized_error = if is_va_gov_service_error
error.class.new({ detail: sanitized_message, source: error_source })
else
error.class.new(sanitized_message)
end
sanitized_error.set_backtrace(error.backtrace)
log_exception_to_rails(sanitized_error, :warn)
end
def cleanup_after_unlock(tempfile_without_pass, unlock_succeeded)
# Always clear password from memory
@password = nil
# Clean up unused tempfile if unlock failed
if tempfile_without_pass && !unlock_succeeded
begin
tempfile_without_pass.close
rescue
nil
end
begin
tempfile_without_pass.unlink
rescue
nil
end
end
end
def unencrypted_pdf?
return unless file_name.match?(/\.pdf$/i) && file_obj
metadata = PdfInfo::Metadata.read(file_obj.tempfile)
errors.add(:base, I18n.t('errors.messages.uploads.encrypted')) if metadata.encrypted?
Rails.logger.info("Document for claim #{claim_id} is encrypted") if metadata.encrypted?
file_obj.tempfile.rewind
rescue PdfInfo::MetadataReadError => e
log_exception_to_rails(e, :warn)
Rails.logger.info("MetadataReadError: Document for claim #{claim_id}")
if e.message.include?('Incorrect password')
errors.add(:base, I18n.t('errors.messages.uploads.pdf.locked'))
else
errors.add(:base, I18n.t('errors.messages.uploads.malformed_pdf'))
end
end
def set_file_extension
self.file_extension = file_name.downcase.split('.').last
end
def normalize_text
return unless file_name.match?(/\.txt$/i) && file_obj
text = file_obj.read
text = text.encode(LIGHTHOUSE_TEXT_ENCODING)
file_obj.tempfile = Tempfile.new(encoding: LIGHTHOUSE_TEXT_ENCODING)
file_obj.tempfile.write text
file_obj.tempfile.rewind
rescue Encoding::UndefinedConversionError
errors.add(:base, I18n.t('errors.messages.uploads.ascii_encoded'))
end
def normalize_file_name
return if !file_name || file_name.frozen?
# remove all but the last "." in the file name
file_name.gsub!(/[.](?=.*[.])/, '')
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/attachment.rb
|
# frozen_string_literal: true
require 'vets/model'
# Attachment model
class Attachment
include Vets::Model
attribute :id, Integer
attribute :message_id, Integer
attribute :name, String
attribute :attachment_size, Integer
attribute :metadata, Hash, default: -> { {} }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/spool_file_event.rb
|
# frozen_string_literal: true
class SpoolFileEvent < ApplicationRecord
validates(:rpo, inclusion: EducationForm::EducationFacility::FACILITY_IDS.values)
validates :filename, uniqueness: { scope: %i[rpo filename] }
# Look for an existing row with same filename and RPO
# and increase retry attempt if wasn't successful from previous attempt
# Otherwise create a new event
def self.build_event(rpo, filename)
filename_rpo_date = filename.match(/(.+)_(.+)_/)[1]
find_by_sql = sanitize_sql_for_conditions(['rpo = :rpo AND filename like :filename',
{ rpo:,
filename: "#{filename_rpo_date}%" }])
event = find_by(find_by_sql)
if event.present?
event.update(retry_attempt: event.retry_attempt + 1) if event.successful_at.nil?
return event
end
create(rpo:, filename:)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/persistent_attachment.rb
|
# frozen_string_literal: true
require 'common/convert_to_pdf'
# Persistent backing of a Shrine file upload, primarily used by SavedClaim
# at the moment.
# create_table "persistent_attachments", id: :serial, force: :cascade do |t|
# t.uuid "guid"
# t.string "type"
# t.string "form_id"
# t.datetime "created_at", null: false
# t.datetime "updated_at", null: false
# t.integer "saved_claim_id"
# t.datetime "completed_at"
# t.text "file_data_ciphertext"
# t.text "encrypted_kms_key"
# t.boolean "needs_kms_rotation", default: false, null: false
# t.integer "doctype"
# t.index ["guid"], name: "index_persistent_attachments_on_guid", unique: true
# t.index ["id", "type"], name: "index_persistent_attachments_on_id_and_type"
# t.index ["needs_kms_rotation"], name: "index_persistent_attachments_on_needs_kms_rotation"
# t.index ["saved_claim_id"], name: "index_persistent_attachments_on_saved_claim_id"
# end
class PersistentAttachment < ApplicationRecord
include SetGuid
ALLOWED_DOCUMENT_TYPES = %w[.pdf .jpg .jpeg .png].freeze
MINIMUM_FILE_SIZE = 1.kilobyte.freeze
has_kms_key
has_encrypted :file_data, key: :kms_key, **lockbox_options
belongs_to :saved_claim, inverse_of: :persistent_attachments, optional: true
delegate :original_filename, :size, to: :file
def to_pdf
Common::ConvertToPdf.new(file).run
end
# Returns the document type associated with the attachment.
# Fallback to a default value of 10 - generic or unspecified document type.
def document_type
doctype || 10
end
# Determines whether stamped PDF validation is required for the attachment.
# @see ClaimDocumentsController#create
#
# @return [Boolean] subclass should override to trigger validation
def requires_stamped_pdf_validation?
false
end
private
def stamp_text
I18n.l(saved_claim.created_at, format: :pdf_stamp)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/education_stem_automated_decision.rb
|
# frozen_string_literal: true
class EducationStemAutomatedDecision < ApplicationRecord
INIT = 'init'
PROCESSED = 'processed'
DENIED = 'denied'
DECISION_STATES = [INIT, PROCESSED, DENIED].freeze
has_kms_key
has_encrypted :auth_headers_json, key: :kms_key, **lockbox_options
validates(:automated_decision_state, inclusion: DECISION_STATES)
belongs_to(:education_benefits_claim, inverse_of: :education_stem_automated_decision)
belongs_to(:user_account, dependent: nil, optional: false)
def self.init
where(automated_decision_state: INIT)
end
def self.processed
where(automated_decision_state: PROCESSED)
end
def self.denied
where(automated_decision_state: DENIED)
end
# @return [Hash] parsed auth headers
#
def auth_headers
return nil if auth_headers_json.nil?
@auth_headers_hash ||= JSON.parse(auth_headers_json)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/message.rb
|
# frozen_string_literal: true
require 'vets/model'
##
# Models a secure message
#
# @!attribute id
# @return [Integer]
# @!attribute category
# @return [String]
# @!attribute subject
# @return [String]
# @!attribute body
# @return [String]
# @!attribute attachment
# @return [Boolean]
# @!attribute sent_date
# @return [Vets::Type::UTCTime]
# @!attribute sender_id
# @return [Integer]
# @!attribute sender_name
# @return [String]
# @!attribute recipient_id
# @return [Integer]
# @!attribute recipient_name
# @return [String]
# @!attribute read_receipt
# @return [String]
# @!attribute triage_group_name
# @return [String]
# @!attribute proxy_sender_name
# @return [String]
# @!attribute attachments
# @return [Array[Attachment]] an array of Attachments
#
class Message
include Vets::Model
include RedisCaching
redis_config REDIS_CONFIG[:secure_messaging_store]
# Only validate presence of category, recipient_id if new message or new draft message
validates :category, :recipient_id, presence: true, unless: proc { reply? }
# Always require body to be present: new message, drafts, and replies
validates :body, presence: true
# Only validate upload sizes if uploads are present.
validate :total_file_count_validation, if: proc { uploads.present? }
validate :each_upload_size_validation, if: proc { uploads.present? }
validate :total_upload_size_validation, if: proc { uploads.present? }
attribute :id, Integer
attribute :category, String
attribute :subject, String, filterable: %w[eq not_eq match]
attribute :body, String
attribute :attachment, Bool, default: false
attribute :sent_date, Vets::Type::UTCTime, filterable: %w[eq lteq gteq]
attribute :sender_id, Integer
attribute :sender_name, String, filterable: %w[eq not_eq match]
attribute :recipient_id, Integer
attribute :recipient_name, String, filterable: %w[eq not_eq match]
attribute :read_receipt, String
attribute :triage_group_name, String
attribute :proxy_sender_name, String
attribute :attachments, Attachment, array: true
attribute :has_attachments, Bool, default: false
attribute :attachment1_id, Integer
attribute :attachment2_id, Integer
attribute :attachment3_id, Integer
attribute :attachment4_id, Integer
attribute :suggested_name_display, String
attribute :is_oh_message, Bool, default: false
attribute :metadata, Hash, default: -> { {} }
attribute :is_large_attachment_upload, Bool, default: false
# This is only used for validating uploaded files, never rendered
attribute :uploads, ActionDispatch::Http::UploadedFile, array: true
##
# @note Default sort should be sent date in descending order
#
default_sort_by sent_date: :desc
set_pagination per_page: 10, max_per_page: 100
alias attachment? attachment
def initialize(attributes = {})
# super is calling Vets::Model#initialize
super(attributes)
# this is called because Vets::Type::Primitive String can't
# coerce html or Nokogiri doc to plain text
# refactoring: the subject & body should be manipulated before passed to Message
@subject = subject ? Nokogiri::HTML.parse(subject).text : nil
@body = body ? Nokogiri::HTML.parse(body).text : nil
end
##
# @note This returns self so that it can be chained: Message.new(params).as_reply
#
def as_reply
@reply = true
self
end
##
# @return [Boolean] is there a reply?
#
def reply?
@reply || false
end
private
def max_single_file_size_mb
is_large_attachment_upload ? 25.0 : 6.0
end
def total_upload_size
return 0 if uploads.blank?
uploads.sum(&:size)
end
def max_total_file_count
is_large_attachment_upload ? 10 : 4
end
def max_total_file_size
is_large_attachment_upload ? 25.0 : 10.0
end
def total_upload_size_validation
return unless total_upload_size > max_total_file_size.megabytes
errors.add(:base, "Total size of uploads exceeds #{max_total_file_size} MB")
end
def each_upload_size_validation
uploads.each do |upload|
next if upload.size <= max_single_file_size_mb.megabytes
errors.add(:base, "The #{upload.original_filename} exceeds file size limit of #{max_single_file_size_mb} MB")
end
end
def total_file_count_validation
return unless uploads.length > max_total_file_count
errors.add(:base, "Total file count exceeds #{max_total_file_count} files")
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/gids_redis.rb
|
# frozen_string_literal: true
require 'common/models/concerns/cache_aside'
require 'gi/client'
require 'gi/search_client'
require 'gi/lcpe/client'
# Facade for GIDS.
class GIDSRedis < Common::RedisStore
include Common::CacheAside
redis_config_key :gids_response
# @return [Symbol] the GI::Client method to call
attr_accessor :rest_call
# @return [Hash] the params to be used with the rest_call
attr_accessor :scrubbed_params
def method_missing(name, *args)
self.rest_call = name
self.scrubbed_params = args.first
if respond_to?(name)
response_from_redis_or_service(gi_service).body
elsif search_respond_to?(name)
response_from_redis_or_service(gi_search_service).body
elsif lcpe_respond_to?(name)
response_from_redis_or_service(gi_lcpe_service).body
else
super
end
end
def respond_to_missing?(name, _include_private)
gi_service.respond_to?(name)
end
def search_respond_to?(name)
gi_search_service.respond_to?(name)
end
def lcpe_respond_to?(name)
gi_lcpe_service.respond_to?(name)
end
private
def response_from_redis_or_service(service)
do_cached_with(key: rest_call.to_s + scrubbed_params.to_s) do
service.send(rest_call, scrubbed_params)
end
end
def gi_service
@client ||= ::GI::Client.new
end
def gi_search_service
@search_client ||= ::GI::SearchClient.new
end
def gi_lcpe_service
@lcpe_client ||= ::GI::LCPE::Client.new
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/session.rb
|
# frozen_string_literal: true
require 'common/models/redis_store'
class Session < Common::RedisStore
redis_store REDIS_CONFIG[:session_store][:namespace]
redis_ttl REDIS_CONFIG[:session_store][:each_ttl]
redis_key :token
DEFAULT_TOKEN_LENGTH = 40
MAX_SESSION_LIFETIME = 12.hours
attribute :token
attribute :uuid
attribute :created_at
attribute :ssoe_transactionid
attribute :profile
attribute :charon_response
attribute :launch
# uuid no longer required as session may be for a system rather than a user
attribute :uuid
validates :token, presence: true
validates :created_at, presence: true
validate :within_maximum_ttl
after_initialize :setup_defaults
def self.obscure_token(token)
Digest::SHA256.hexdigest(token)[0..20]
end
def expire(ttl)
return false if invalid?
super(ttl)
end
def ttl_in_time
Time.current.utc + ttl
end
def authenticated_by_ssoe
@ssoe_transactionid.present?
end
private
def secure_random_token(length = DEFAULT_TOKEN_LENGTH)
loop do
# copied from: https://github.com/plataformatec/devise/blob/master/lib/devise.rb#L475-L482
rlength = (length * 3) / 4
random_token = SecureRandom.urlsafe_base64(rlength).tr('lIO0', 'sxyz')
break random_token unless self.class.exists?(random_token) == 1
end
end
def setup_defaults
@token ||= secure_random_token
@created_at ||= Time.now.utc
end
def within_maximum_ttl
time_remaining = (@created_at + MAX_SESSION_LIFETIME - Time.now.utc).round
if time_remaining.negative?
Rails.logger.info('[Session] Maximum Session Duration Reached',
session_token: self.class.obscure_token(@token))
errors.add(:created_at, "is more than the max of [#{MAX_SESSION_LIFETIME}] seconds. Session is too old")
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/all_triage_teams.rb
|
# frozen_string_literal: true
require 'vets/model'
# AllTriageTeams model
class AllTriageTeams
include Vets::Model
include RedisCaching
redis_config REDIS_CONFIG[:secure_messaging_store]
attribute :triage_team_id, Integer
attribute :name, String
attribute :station_number, String
attribute :blocked_status, Bool, default: false
attribute :preferred_team, Bool, default: false
attribute :relation_type, String
attribute :lead_provider_name, String
attribute :location_name, String
attribute :lead_provider_name, String
attribute :team_name, String
attribute :suggested_name_display, String
attribute :health_care_system_name, String
attribute :group_type_enum_val, String
attribute :sub_group_type_enum_val, String
attribute :group_type_patient_display, String
attribute :sub_group_type_patient_display, String
attribute :oh_triage_group, Bool, default: false
default_sort_by name: :asc
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/deprecated_user_account.rb
|
# frozen_string_literal: true
class DeprecatedUserAccount < ApplicationRecord
belongs_to :user_verification, dependent: nil
belongs_to :user_account, dependent: :destroy
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/gibs_not_found_user.rb
|
# frozen_string_literal: true
class GibsNotFoundUser < ApplicationRecord
# :nocov:
has_kms_key
has_encrypted :ssn, key: :kms_key, **lockbox_options
validates :edipi, presence: true, uniqueness: true
validates :first_name, :last_name, :ssn_ciphertext, :dob, presence: true
def self.log(user)
create_with(
first_name: user.first_name,
last_name: user.last_name,
ssn: user.ssn,
dob: user.birth_date
).find_or_create_by(edipi: user.edipi)
end
# :nocov:
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/iam_user.rb
|
# frozen_string_literal: true
require 'digest'
require 'active_support/core_ext/digest/uuid'
require 'common/client/errors'
# Subclasses the `User` model. Adds a unique redis namespace for IAM users.
# Adds IAM sourced versions of ICN, EDIPI, and SEC ID and methods to use them
# or hit MPI via the mpi_profile.
#
class IAMUser < User
redis_store REDIS_CONFIG[:iam_user][:namespace]
redis_ttl REDIS_CONFIG[:iam_user][:each_ttl]
redis_key :uuid
attribute :expiration_timestamp, Integer
attribute :iam_edipi, String
attribute :iam_sec_id, String
attribute :iam_mhv_id, String
alias mhv_correlation_id iam_mhv_id
# Builds an user instance from a IAMUserIdentity
#
# @param iam_identity [IAMUserIdentity] the IAM identity object.
# @return [IAMUser] an instance of this class
#
def self.build_from_user_identity(user_identity)
user = new(user_identity.attributes)
user.set_expire
user
end
# Where to get the edipi from
# If iam_edipi available return that otherwise hit MVI
# @return [String] the users DoD EDIPI
#
def edipi
loa3? && iam_edipi.present? ? iam_edipi : mpi&.edipi
end
# Return the uuid as the id for the user. This id is generated
# within the IAMUserIdentity class.
# @return [String] UUID that is unique to this user
#
def id
uuid
end
def common_name
"#{identity.first_name} #{identity.last_name}"
end
def identity
@identity ||= IAMUserIdentity.find(uuid)
end
def sec_id
identity.iam_sec_id || sec_id
end
def mhv_account_type
MHVAccountTypeService.new(self).mhv_account_type
end
# This is not the correct way of determining VA patient status,
# but it works for authorizing access for existing MHV premium users
# If we are going to enable account creation/upgrade, then we'll need
# to derive the list of facilities from the IAM introspection payload.
def va_patient?
mhv_correlation_id.present?
end
def set_expire
redis_namespace.expireat(REDIS_CONFIG[:iam_user][:namespace], expiration_timestamp)
end
def vet360_contact_info
super
rescue Faraday::ResourceNotFound
raise Common::Exceptions::RecordNotFound, vet360_id
rescue Common::Client::Errors::ClientError
raise Common::Exceptions::BadGateway.new(id: vet360_id)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/onsite_notification.rb
|
# frozen_string_literal: true
class OnsiteNotification < ApplicationRecord
validates :template_id, :va_profile_id, presence: true
validates :template_id, inclusion: Settings.onsite_notifications.template_ids
def self.for_user(user, include_dismissed: false)
notifications = where(va_profile_id: user.vet360_id).order(created_at: :desc)
return notifications if include_dismissed
notifications.where(dismissed: false)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/power_of_attorney.rb
|
# frozen_string_literal: true
require 'vets/model'
# PowerOfAttorney model
class PowerOfAttorney
include Vets::Model
attribute :social_security_number, String
attribute :code, String
attribute :name, String
attribute :organization, String
attribute :begin_date, String
attribute :end_date, String
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/message_draft.rb
|
# frozen_string_literal: true
##
# Models Message draft
# @note drafts are essentially messages with an implied folder (drafts), and if a reply, an implied message
#
# @!attribute has_message
# @return [Boolean]
#
class MessageDraft < Message
validate :check_as_replydraft, if: proc { reply? }
validate :check_as_draft, unless: proc { reply? }
attribute :has_message, Bool, default: false
def message?
has_message
end
private
def check_as_replydraft
errors.add(:base, 'This draft requires a reply-to message.') unless message?
end
def check_as_draft
errors.add(:base, 'This draft cannot have a reply-to message') if message?
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/tooltip.rb
|
# frozen_string_literal: true
class Tooltip < ApplicationRecord
belongs_to :user_account, inverse_of: :tooltips
validates :tooltip_name, presence: true, uniqueness: { scope: :user_account_id }
validates :last_signed_in, presence: true
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/supporting_evidence_attachment.rb
|
# frozen_string_literal: true
# Files uploaded as part of a form526 submission that will be sent to EVSS upon form submission.
# inherits from ApplicationRecord
class SupportingEvidenceAttachment < FormAttachment
ATTACHMENT_UPLOADER_CLASS = SupportingEvidenceAttachmentUploader
FILENAME_EXTENSION_MATCHER = /\.\w*$/
OBFUSCATED_CHARACTER_MATCHER = /[a-zA-Z\d]/
# this uploads the file to S3 through its parent class
# the final filename comes from the uploader once the file is successfully uploaded to S3
def set_file_data!(file, file_password = nil)
file_data_json = super
au = get_attachment_uploader
if au.converted_exists?
self.file_data = JSON.parse(file_data_json).merge('converted_filename' => au.final_filename).to_json
end
file_data
end
def converted_filename
parsed_file_data['converted_filename']
end
def original_filename
parsed_file_data['filename']
end
# Obfuscates the attachment's file name for use in mailers, so we don't email PII
# The intent is the file should still be recognizable to the veteran who uploaded it
# Follows these rules:
# - Only masks filenames longer than 5 characters
# - Masks letters and numbers, but preserves special characters
# - Includes the file extension
def obscured_filename
extension = original_filename[FILENAME_EXTENSION_MATCHER]
filename_without_extension = original_filename.gsub(FILENAME_EXTENSION_MATCHER, '')
if filename_without_extension.length > 5
# Obfuscate with the letter 'X'; we cannot obfuscate with special characters such as an asterisk,
# as these filenames appear in VA Notify Mailers and their templating engine uses markdown.
# Therefore, special characters can be interpreted as markdown and introduce formatting issues in the mailer
obfuscated_portion = filename_without_extension[3..-3].gsub(OBFUSCATED_CHARACTER_MATCHER, 'X')
filename_without_extension[0..2] + obfuscated_portion + filename_without_extension[-2..] + extension
else
original_filename
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/folder.rb
|
# frozen_string_literal: true
require 'vets/model'
# Folder model
class Folder
include Vets::Model
include RedisCaching
redis_config REDIS_CONFIG[:secure_messaging_store]
attribute :id, Integer
attribute :name, String
attribute :count, Integer
attribute :unread_count, Integer
attribute :system_folder, Bool, default: false
attribute :metadata, Hash, default: -> { {} }
validates :name, presence: true, folder_name_convention: true, length: { maximum: 50 }
alias system_folder? system_folder
default_sort_by name: :asc
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/education_benefits_claim.rb
|
# frozen_string_literal: true
class EducationBenefitsClaim < ApplicationRecord
FORM_TYPES = %w[
1990
1995
5490
5495
0993
0994
10203
10282
10216
10215
10297
1919
0839
10275
8794
0976
0803
].freeze
APPLICATION_TYPES = %w[
chapter33
chapter1607
chapter1606
chapter32
chapter35
transfer_of_entitlement
vettec
chapter30
vrrap
].freeze
belongs_to(:saved_claim, class_name: 'SavedClaim::EducationBenefits', inverse_of: :education_benefits_claim)
has_one(:education_benefits_submission, inverse_of: :education_benefits_claim)
has_one(:education_stem_automated_decision, inverse_of: :education_benefits_claim, dependent: :destroy)
delegate(:parsed_form, to: :saved_claim)
delegate(:form, to: :saved_claim)
before_validation :set_token, on: :create
before_save(:set_region)
after_create(:create_education_benefits_submission)
after_save(:update_education_benefits_submission_status)
# For console access only, right now.
def reprocess_at(region)
key = region.to_sym
unless EducationForm::EducationFacility::REGIONS.include?(key)
raise "Invalid region. Must be one of #{EducationForm::EducationFacility::REGIONS.join(', ')}"
end
self.regional_processing_office = region
self.processed_at = nil
save
end
def confirmation_number
"V-EBC-#{id}"
end
FORM_TYPES.each do |type|
define_method("is_#{type}?") do
form_type == type
end
end
def form_type
saved_claim.form_id.gsub('22-', '').downcase
end
# This converts the form data into an OpenStruct object so that the template
# rendering can be cleaner. Piping it through the JSON serializer was a quick
# and easy way to deeply transform the object.
def open_struct_form
@application ||= lambda do
@application = saved_claim.open_struct_form
@application.confirmation_number = confirmation_number
transform_form
@application
end.call
end
def transform_form
generate_benefits_to_apply_to if is_1990?
copy_from_previous_benefits if is_5490?
end
def copy_from_previous_benefits
if @application.currentSameAsPrevious
previous_benefits = @application.previousBenefits
%w[veteranFullName vaFileNumber veteranSocialSecurityNumber].each do |attr|
@application.public_send("#{attr}=", previous_benefits.public_send(attr))
end
end
end
def generate_benefits_to_apply_to
selected_benefits = []
APPLICATION_TYPES.each do |application_type|
selected_benefits << application_type if @application.public_send(application_type)
end
selected_benefits = selected_benefits.join(', ')
@application.toursOfDuty&.each do |tour|
tour.benefitsToApplyTo = selected_benefits if tour.applyPeriodToSelected
end
end
def self.unprocessed
where(processed_at: nil)
end
def region
EducationForm::EducationFacility.region_for(self)
end
def regional_office
EducationForm::EducationFacility.regional_office_for(self)
end
def selected_benefits
benefits = {}
case form_type
when '1990'
benefits = parsed_form.slice(*APPLICATION_TYPES)
when '0994', '10297'
benefits['vettec'] = true
when '1995'
benefit = parsed_form['benefit']&.underscore
benefits['chapter33'] = true if benefit.present? && benefit.start_with?('chapter33')
benefits[benefit] = true if benefit.present? && !benefit.start_with?('chapter33')
else
benefit = parsed_form['benefit']&.underscore
benefits[benefit] = true if benefit.present?
end
benefits
end
def self.form_headers(form_types = FORM_TYPES)
form_types.map { |t| "22-#{t}" }.freeze
end
private
def create_education_benefits_submission
opt = selected_benefits
EducationBenefitsSubmission.create!(
opt.merge(
region:,
form_type:,
education_benefits_claim: self
)
)
end
def update_education_benefits_submission_status
if processed_at.present? && attribute_before_last_save(:processed).nil?
# old claims don't have an education benefits submission associated
education_benefits_submission&.update!(status: 'processed')
end
end
def set_region
self.regional_processing_office ||= region.to_s
end
def set_token
self.token ||= SecureRandom.hex
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/excel_file_event.rb
|
# frozen_string_literal: true
class ExcelFileEvent < ApplicationRecord
validates :filename, uniqueness: true
# Look for an existing row with same filename
# and increase retry attempt if wasn't successful from previous attempt
# Otherwise create a new event
def self.build_event(filename)
filename_date = filename.match(/(.+)_/)[1]
event = find_by('filename like ?', "#{filename_date}%")
if event.present?
event.update(retry_attempt: event.retry_attempt + 1) if event.successful_at.nil?
return event
end
create(filename:)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/form_submission.rb
|
# frozen_string_literal: true
class FormSubmission < ApplicationRecord
has_kms_key
has_encrypted :form_data, key: :kms_key, **lockbox_options
has_many :form_submission_attempts, dependent: :destroy
belongs_to :saved_claim, optional: true
belongs_to :user_account, optional: true
validates :form_type, presence: true
class << self
def with_latest_benefits_intake_uuid(user_account)
select('form_submissions.id, form_submissions.form_type, la.benefits_intake_uuid, form_submissions.created_at')
.from('form_submissions')
.joins(
"LEFT JOIN (#{FormSubmissionAttempt.latest_attempts.to_sql}) AS la " \
'ON form_submissions.id = la.form_submission_id'
)
.order('form_submissions.id')
.where(user_account:)
end
def with_form_types(form_types)
if form_types.present?
where(form_type: form_types)
else
where.not(form_type: nil)
end
end
end
def latest_attempt
form_submission_attempts.order(created_at: :asc).last
end
def latest_pending_attempt
form_submission_attempts.where(aasm_state: 'pending').order(created_at: :asc).last
end
def non_failure_attempt
form_submission_attempts.where(aasm_state: %w[pending success]).first
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/dependents_application.rb
|
# frozen_string_literal: true
require 'string_helpers'
class DependentsApplication < Common::RedisStore
include RedisForm
validates(:user, presence: true, unless: :persisted?)
validate(:user_can_access_evss, unless: :persisted?)
FORM_ID = '21-686C'
SEPARATION_TYPES = {
'Death' => 'DEATH',
'Divorce' => 'DIVORCED',
'Other' => 'OTHER'
}.freeze
MILITARY_STATES = %w[AA AE AP].freeze
def self.filter_children(dependents, evss_children)
return [] if evss_children.blank? || dependents.blank?
evss_children.find_all do |child|
ssn = child['ssn'].delete('-')
dependents.find do |dependent|
dependent['childSocialSecurityNumber'] == ssn
end
end
end
def self.convert_evss_date(date)
Date.parse(date).to_time(:utc).iso8601
end
def self.convert_name(full_name)
full_name ||= {}
full_name.transform_keys { |k| "#{k}Name" }
end
def self.convert_ssn(ssn)
return {} if ssn.blank?
{
'ssn' => StringHelpers.hyphenated_ssn(ssn),
'hasNoSsn' => false,
'noSsnReasonType' => nil
}
end
def self.get_address_locality(address)
if address['country'] == 'USA'
MILITARY_STATES.include?(address['state']) ? 'MILITARY' : 'DOMESTIC'
else
'INTERNATIONAL'
end
end
def self.convert_address(address)
converted = {}
return converted if address.blank?
converted['address'] = {
'addressLine1' => address['street'],
'addressLine2' => address['street2'],
'addressLine3' => address['street3'],
'addressLocality' => get_address_locality(address),
'city' => address['city'],
'country' => convert_country(address),
'postOffice' => address['postOffice'],
'postalType' => address['postalType'],
'state' => address['state'],
'zipCode' => address['postalCode']
}
converted
end
def self.convert_country(location)
return {} if location.blank?
{
'dropDownCountry' => location['countryDropdown'],
'textCountry' => location['countryText']
}
end
def self.convert_previous_marriages(previous_marriages)
return [] if previous_marriages.blank?
previous_marriages.map do |previous_marriage|
location_separation = previous_marriage['locationOfSeparation'] || {}
{
'marriageDate' => convert_evss_date(previous_marriage['dateOfMarriage']),
'endCity' => location_separation['city'],
'city' => previous_marriage['locationOfMarriage']['city'],
'endCountry' => convert_country(location_separation),
'country' => convert_country(previous_marriage['locationOfMarriage']),
'terminatedDate' => convert_evss_date(previous_marriage['dateOfSeparation']),
'marriageTerminationReasonType' => SEPARATION_TYPES[previous_marriage['reasonForSeparation']],
'explainTermination' => previous_marriage['explainSeparation'],
'endState' => location_separation['state'],
'state' => previous_marriage['locationOfMarriage']['state']
}.merge(
convert_name(previous_marriage['spouseFullName'])
)
end
end
def self.convert_marriage(current_marriage, last_marriage, spouse_marriages)
converted = {}
return converted if current_marriage.blank?
converted.merge!(convert_address(current_marriage['spouseAddress']))
converted.merge!(convert_name(last_marriage['spouseFullName']))
converted.merge!(convert_no_ssn(current_marriage['spouseHasNoSsn'], current_marriage['spouseHasNoSsnReason']))
converted.merge!(convert_ssn(current_marriage['spouseSocialSecurityNumber']))
converted['dateOfBirth'] = convert_evss_date(current_marriage['spouseDateOfBirth'])
converted['currentMarriage'] = {
'marriageDate' => convert_evss_date(last_marriage['dateOfMarriage']),
'city' => last_marriage['locationOfMarriage']['city'],
'country' => convert_country(last_marriage['locationOfMarriage']),
'state' => last_marriage['locationOfMarriage']['state']
}
converted['vaFileNumber'] = convert_ssn(current_marriage['spouseVaFileNumber'])['ssn']
converted['veteran'] = current_marriage['spouseIsVeteran']
converted['previousMarriages'] = convert_previous_marriages(spouse_marriages)
converted
end
def self.convert_no_ssn(no_ssn, reason_type)
{
'hasNoSsn' => no_ssn,
'noSsnReasonType' => reason_type
}
end
def self.set_child_attrs!(dependent, home_address, child = {})
child.merge!(convert_name(dependent['fullName']))
set_child_address!(dependent, home_address, child)
set_place_of_birth!(dependent['childPlaceOfBirth'], child)
set_guardian!(dependent['personWhoLivesWithChild'], child)
set_ssn_info!(dependent, child)
set_relationship_type!(dependent, child)
set_boolean_attrs!(dependent, child)
set_date_attrs!(dependent, child)
child
end
def self.set_child_address!(dependent, home_address, child)
if dependent['childInHousehold']
child.merge!(home_address)
else
child.merge!(convert_address(dependent['childAddress']))
end
end
def self.set_place_of_birth!(place_of_birth, child)
return if place_of_birth.blank?
child['countryOfBirth'] = convert_country(place_of_birth)
child['cityOfBirth'] = place_of_birth['city']
child['stateOfBirth'] = place_of_birth['state']
end
def self.set_guardian!(guardian, child)
guardian ||= {}
child['guardianFirstName'] = guardian['first']
child['guardianMiddleName'] = guardian['middle']
child['guardianLastName'] = guardian['last']
end
def self.set_ssn_info!(dependent, child)
child.merge!(convert_no_ssn(dependent['childHasNoSsn'], dependent['childHasNoSsnReason']))
child.merge!(convert_ssn(dependent['childSocialSecurityNumber']))
end
def self.set_relationship_type!(dependent, child)
child['childRelationshipType'] = dependent['childRelationship']&.upcase
end
def self.set_boolean_attrs!(dependent, child)
[
%w[attendedSchool attendingCollege],
%w[disabled disabled],
%w[married previouslyMarried]
].each do |attrs|
val = dependent[attrs[1]]
next if val.nil?
child[attrs[0]] = val
end
end
def self.set_date_attrs!(dependent, child)
[
%w[dateOfBirth childDateOfBirth],
%w[marriedDate marriedDate]
].each do |attrs|
val = dependent[attrs[1]]
next if val.blank?
child[attrs[0]] = convert_evss_date(val)
end
end
def self.transform_form(parsed_form, evss_form)
transformed = {}
transformed['spouse'] = transform_spouse(parsed_form, evss_form)
transformed['children'] = transform_children(parsed_form, evss_form)
transformed['marriageType'] = parsed_form['maritalStatus']
previous_marriages = separate_previous_marriages(parsed_form['marriages'])
transformed['previousMarriages'] = convert_previous_marriages(previous_marriages)
evss_form['submitProcess']['veteran'].merge!(transformed)
Common::HashHelpers.deep_compact(evss_form)
end
def self.transform_spouse(parsed_form, evss_form)
spouse = convert_marriage(
parsed_form['currentMarriage'],
parsed_form['marriages']&.last,
parsed_form['spouseMarriages']
)
home_address = evss_form['submitProcess']['veteran'].slice('address')
spouse.merge!(home_address) if parsed_form['currentMarriage']&.dig('liveWithSpouse')
spouse
end
def self.transform_children(parsed_form, evss_form)
dependents = parsed_form['dependents'] || []
home_address = evss_form['submitProcess']['veteran'].slice('address')
children = filter_children(
dependents,
evss_form['submitProcess']['veteran']['children']
)
dependents.each do |dependent|
child = children.find { |c| c['ssn'] == dependent['childSocialSecurityNumber'] }
if child
set_child_attrs!(dependent, home_address, child)
else
children << set_child_attrs!(dependent, home_address)
end
end
children
end
def self.separate_previous_marriages(marriages)
marriages&.find_all do |marriage|
marriage['dateOfSeparation'].present?
end
end
private
def user_can_access_evss
errors.add(:user, 'must have evss access') unless user.authorize(:evss, :access?)
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/submission.rb
|
# frozen_string_literal: true
require 'json_marshal/marshaller'
# Concern to add encryption columns to Submission class
module SubmissionEncryption
extend ActiveSupport::Concern
included do
serialize :reference_data, coder: JsonMarshal::Marshaller
has_kms_key
has_encrypted :reference_data, key: :kms_key, **lockbox_options
end
end
# Representation of an abstract Submission to a service
class Submission < ApplicationRecord
self.abstract_class = true
validates :form_id, presence: true
has_many :submission_attempts, dependent: :destroy
def latest_attempt
submission_attempts&.order(created_at: :desc)&.first
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/submission_attempt.rb
|
# frozen_string_literal: true
require 'json_marshal/marshaller'
# Concern to add encryption columns to SubmissionAttempt class
module SubmissionAttemptEncryption
extend ActiveSupport::Concern
included do
serialize :metadata, coder: JsonMarshal::Marshaller
serialize :error_message, coder: JsonMarshal::Marshaller
serialize :response, coder: JsonMarshal::Marshaller
has_kms_key
has_encrypted :metadata, key: :kms_key, **lockbox_options
has_encrypted :error_message, key: :kms_key, **lockbox_options
has_encrypted :response, key: :kms_key, **lockbox_options
end
end
# Representation of an abstract SubmissionAttempt to a service
class SubmissionAttempt < ApplicationRecord
self.abstract_class = true
validates :submission, presence: true
after_create :update_submission_status
before_update :update_submission_status
private
def update_submission_status
submission.update(latest_status: status) if status_changed? || id_previously_changed?
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user_account.rb
|
# frozen_string_literal: true
class UserAccount < ApplicationRecord
has_many :form_submissions, dependent: :nullify
has_many :user_verifications, dependent: :destroy
has_many :terms_of_use_agreements, dependent: :destroy
has_many :tooltips, dependent: :destroy
has_one :user_acceptable_verified_credential, dependent: :destroy
has_one :veteran_onboarding, primary_key: :uuid, foreign_key: :user_account_uuid, inverse_of: :user_account,
dependent: :destroy
validates :icn, uniqueness: true, allow_nil: true
def verified?
icn.present?
end
def needs_accepted_terms_of_use?
verified? && !accepted_current_terms_of_use?
end
private
def accepted_current_terms_of_use?
terms_of_use_agreements.current.last&.accepted?
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/accredited_individual.rb
|
# frozen_string_literal: true
require 'accredited_representation/constants'
class AccreditedIndividual < ApplicationRecord
# Represents an accredited individual (attorney, claims agent, representative) as defined by the OGC accreditation
# APIs. Until a form of soft deletion is implemented, these records will only reflect individuals with active
# accreditation.
#
# Key notes:
# 1. The core record attributes are populated from the OGC accreditation APIs, not the files found at
# https://www.va.gov/ogc/apps/accreditation/ that Veteran::Service::Representative uses.
# 2. The intent of raw_address is to store the address as supplied by OGC for diffing purposes to avoid excess API
# calls. Those addresses are not verified and do not contain latitude and longitude. The address information stored
# on the record comes from the Lighthouse Address Validation API so that geolocation searching is supported
# for the Find A Representative feature.
# 3. The representative type should not have a POA code assigned. Representatives should only be associated with the
# POA codes of the AccreditedOrganizations they are accredited with.
# 4. Attorneys and claims agents should have a POA code and should not be accredited with any AccreditedOrganization
# 5. The ogc_id is the id from the source table within OGC. It can be used to interact with their show endpoints
# and may be nice to have for troubleshooting purposes.
has_many :accreditations, dependent: :destroy
has_many :accredited_organizations, through: :accreditations
validates :ogc_id, :registration_number, :individual_type, presence: true
validates :poa_code, length: { is: 3 }, allow_blank: true
validates :individual_type, uniqueness: { scope: :registration_number }
enum :individual_type, {
'attorney' => 'attorney',
'claims_agent' => 'claims_agent',
'representative' => 'representative'
}
before_save :set_full_name
# Set the full_name attribute for the representative
def set_full_name
self.full_name = [first_name, last_name].map(&:to_s).map(&:strip).compact_blank.join(' ')
end
DEFAULT_FUZZY_THRESHOLD = AccreditedRepresentation::Constants::FUZZY_SEARCH_THRESHOLD
# Find all [AccreditedIndividuals] that are located within a distance of a specific location
# @param long [Float] longitude of the location of interest
# @param lat [Float] latitude of the location of interest
# @param max_distance [Float] the maximum search distance in meters
#
# @return [AccreditedIndividual::ActiveRecord_Relation] an ActiveRecord_Relation of
# all individuals matching the search criteria
def self.find_within_max_distance(long, lat, max_distance = AccreditedRepresentation::Constants::DEFAULT_MAX_DISTANCE)
query = 'ST_DWithin(ST_SetSRID(ST_MakePoint(:long, :lat), 4326)::geography,' \
'accredited_individuals.location, :max_distance)'
params = { long:, lat:, max_distance: }
where(query, params)
end
#
# Find all [AccreditedIndividuals] with a full name with at least the threshold value of
# word similarity. This gives us a way to fuzzy search for names.
# @param search_phrase [String] the word, words, or phrase we want individuals with full names similar to
# @param threshold [Float] the strictness of word matching between 0 and 1. Values closer to zero allow for words to
# be less similar.
#
# @return [AccreditedIndividual::ActiveRecord_Relation] an ActiveRecord_Relation of
# all individuals matching the search criteria
def self.find_with_full_name_similar_to(search_phrase, threshold = DEFAULT_FUZZY_THRESHOLD)
where('word_similarity(?, accredited_individuals.full_name) >= ?', search_phrase, threshold)
end
# return all poa_codes associated with the individual
#
# @return [Array<String>]
def poa_codes
([poa_code] + accredited_organizations.pluck(:poa_code)).compact
end
# This method needs to exist on the model so [Common::Collection] doesn't blow up when trying to paginate
def self.max_per_page
AccreditedRepresentation::Constants::MAX_PER_PAGE
end
# Validates and updates the address for this individual
#
# Uses the raw_address field (populated from OGC API) to call the address validation service.
# If validation is successful, updates the record with validated address data including
# geocoded coordinates.
#
# @return [Boolean] true if validation and update successful, false otherwise
def validate_address
return false if raw_address.blank?
service = RepresentationManagement::AddressValidationService.new
validated_attrs = service.validate_address(raw_address)
return false if validated_attrs.nil?
update(validated_attrs)
rescue => e
Rails.logger.error("Address validation failed for AccreditedIndividual #{id}: #{e.message}")
false
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/feature_toggle_event.rb
|
# frozen_string_literal: true
class FeatureToggleEvent < ApplicationRecord
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/messaging_preference.rb
|
# frozen_string_literal: true
require 'vets/model'
require 'va_profile/models/email'
# Secure Messaging Notification Preference Model
class MessagingPreference
include Vets::Model
FREQUENCY_UPDATE_MAP = {
'none' => 0,
'each_message' => 1,
'daily' => 2
}.freeze
FREQUENCY_GET_MAP = {
'None' => 'none',
'Each message' => 'each_message',
'Once daily' => 'daily'
}.freeze
attribute :email_address, String
attribute :frequency, String
validates :frequency, presence: true, inclusion: { in: FREQUENCY_UPDATE_MAP.keys }
validates(
:email_address,
presence: true,
format: { with: VAProfile::Models::Email::VALID_EMAIL_REGEX },
length: { maximum: 255, minimum: 6 }
)
def mhv_params
raise Common::Exceptions::ValidationErrors, self unless valid?
{ email_address:, notify_me: FREQUENCY_UPDATE_MAP.fetch(frequency) }
end
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/user_identity.rb
|
# frozen_string_literal: true
require 'common/models/base'
require 'common/models/redis_store'
require 'saml/user'
# Stores attributes used to identify a user. Serves as a set of inputs to an MVI lookup. Also serves
# as the receiver of identity attributes received from alternative sources during the SSO flow.
class UserIdentity < Common::RedisStore
redis_store REDIS_CONFIG[:user_identity_store][:namespace]
redis_ttl REDIS_CONFIG[:user_identity_store][:each_ttl]
redis_key :uuid
# identity attributes
attribute :uuid
attribute :email
attribute :first_name
attribute :middle_name
attribute :last_name
attribute :gender
attribute :birth_date
attribute :icn
attribute :ssn
attribute :loa
attribute :multifactor, Boolean # used by F/E to decision on whether or not to prompt user to add MFA
attribute :authn_context # used by F/E to handle various identity related complexities pending refactor
attribute :idme_uuid
attribute :logingov_uuid
attribute :verified_at # Login.gov IAL2 verification timestamp
attribute :sec_id
attribute :mhv_icn # only needed by B/E not serialized in user_serializer
attribute :mhv_credential_uuid
attribute :mhv_account_type # this is only available for MHV sign-in users
attribute :edipi # this is only available for dslogon users
attribute :sign_in, Hash # original sign_in (see sso_service#mergable_identity_attributes)
attribute :icn_with_aaid
attribute :search_token
validates :uuid, presence: true
validates :loa, presence: true
validate :loa_highest_present
# LOA3 no longer just means ID.me FICAM LOA3.
# It could also be DSLogon or MHV Premium users.
# It could also be DSLogon or MHV NON PREMIUM users who have done ID.me FICAM LOA3.
# Additionally, LOA3 does not automatically mean user has opted to have MFA.
def loa3?
loa && loa[:current].try(:to_i) == LOA::THREE
end
with_options if: :loa3? do
validates :ssn, format: /\A\d{9}\z/, allow_blank: true
validates :gender, format: /\A(M|F)\z/, allow_blank: true
end
private
def loa_highest_present
errors.add(:loa, 'loa[:highest] is not present!') if loa[:highest].blank?
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/education_benefits_submission.rb
|
# frozen_string_literal: true
class EducationBenefitsSubmission < ApplicationRecord
# don't delete this table, we need to keep the data for a report
validates(:region, presence: true)
validates(:region, inclusion: EducationForm::EducationFacility::REGIONS.map(&:to_s))
validates(:status, inclusion: %w[processed submitted])
validates(:form_type, inclusion: EducationBenefitsClaim::FORM_TYPES)
belongs_to(:education_benefits_claim, inverse_of: :education_benefits_submission)
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user_profile_attributes.rb
|
# frozen_string_literal: true
require 'common/models/base'
require 'common/models/redis_store'
# Stores attributes used to identify a user. Serves as a set of inputs to an MVI lookup. Also serves
# as the receiver of identity attributes received from alternative sources during the SSO flow.
class UserProfileAttributes < Common::RedisStore
redis_store REDIS_CONFIG[:user_profile_attributes][:namespace]
redis_ttl REDIS_CONFIG[:user_profile_attributes][:each_ttl]
redis_key :uuid
# identity attributes
attribute :uuid
attribute :icn
attribute :email
attribute :first_name
attribute :last_name
attribute :ssn
attribute :flipper_id
validates :uuid, presence: true
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/disability_contention.rb
|
# frozen_string_literal: true
class DisabilityContention < ApplicationRecord
validates :code, presence: true, uniqueness: true
validates :medical_term, presence: true
def self.suggested(name_part)
DisabilityContention.where('medical_term ILIKE ? OR lay_term ILIKE ?', "%#{name_part}%", "%#{name_part}%")
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/accreditation.rb
|
# frozen_string_literal: true
class Accreditation < ApplicationRecord
# Acts as the join between AccreditedIndividual and AccreditedOrganization and is meant to store information that
# lives at the grain between the two models. For example, can_accept_reject_poa is a permission that needs to be
# set for each organization a representative is accredited with.
#
# @note for can_accept_reject_poa that a slight change
# to implementation might be needed to support attorneys and claims agents since they do not have organization
# accreditations.
belongs_to :accredited_individual
belongs_to :accredited_organization
validates :accredited_organization_id, uniqueness: { scope: :accredited_individual_id }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/message_thread.rb
|
# frozen_string_literal: true
require 'vets/model'
class MessageThread
include Vets::Model
attribute :thread_id, Integer
attribute :folder_id, Integer
attribute :message_id, Integer
attribute :thread_page_size, Integer
attribute :message_count, Integer
attribute :category, String
attribute :subject, String
attribute :triage_group_name, String
attribute :sent_date, Vets::Type::UTCTime
attribute :draft_date, Vets::Type::UTCTime
attribute :sender_id, Integer
attribute :sender_name, String
attribute :recipient_name, String
attribute :recipient_id, Integer
attribute :proxySender_name, String
attribute :has_attachment, Bool, default: false
attribute :thread_has_attachment, Bool, default: false
attribute :unsent_drafts, Bool, default: false
attribute :unread_messages, Bool, default: false
attribute :is_oh_message, Bool, default: false
attribute :suggested_name_display, String
def initialize(attributes = {})
super(attributes)
@subject = subject ? Nokogiri::HTML.parse(subject).text : nil
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/central_mail_submission.rb
|
# frozen_string_literal: true
class CentralMailSubmission < ApplicationRecord
belongs_to(:central_mail_claim, inverse_of: :central_mail_submission, foreign_key: 'saved_claim_id')
validates(:state, presence: true, inclusion: %w[success failed pending])
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/accredited_organization.rb
|
# frozen_string_literal: true
require 'accredited_representation/constants'
class AccreditedOrganization < ApplicationRecord
# Represents an accredited organization as defined by the OGC accreditation APIs. Until a form of soft deletion is
# implemented, these records will only reflect organization with active accreditation.
#
# Key notes:
# 1. The core record attributes are populated from the OGC accreditation APIs, not the files found at
# https://www.va.gov/ogc/apps/accreditation/ that Veteran::Service::Organization uses.
# 2. The intent of raw_address is to store the address as supplied by OGC for diffing purposes to avoid excess API
# calls. Those addresses are not verified and do not contain latitude and longitude. The address information stored
# on the record comes from the Lighthouse Address Validation API so that geolocation searching is supported
# for the Find A Representative feature.
# 3. The ogc_id is the id from the source table within OGC. It can be used to interact with their show endpoints
# and may be nice to have for troubleshooting purposes.
has_many :accreditations, dependent: :destroy
has_many :accredited_individuals, through: :accreditations
validates :ogc_id, :poa_code, presence: true
validates :poa_code, length: { is: 3 }
validates :poa_code, uniqueness: true
#
# Find all [AccreditedOrganizations] that are located within a distance of a specific location
# @param long [Float] longitude of the location of interest
# @param lat [Float] latitude of the location of interest
# @param max_distance [Float] the maximum search distance in meters
#
# @return [AccreditedOrganization::ActiveRecord_Relation] an ActiveRecord_Relation of
# all organizations matching the search criteria
def self.find_within_max_distance(long, lat, max_distance = AccreditedRepresentation::Constants::DEFAULT_MAX_DISTANCE)
query = 'ST_DWithin(ST_SetSRID(ST_MakePoint(:long, :lat), 4326)::geography,' \
'accredited_organizations.location, :max_distance)'
params = { long:, lat:, max_distance: }
where(query, params)
end
# return all registration_numbers associated with the organization
#
# @return [Array<String>]
def registration_numbers
accredited_individuals.pluck(:registration_number)
end
# This method needs to exist on the model so [Common::Collection] doesn't blow up when trying to paginate
def self.max_per_page
AccreditedRepresentation::Constants::MAX_PER_PAGE
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user_action_event.rb
|
# frozen_string_literal: true
class UserActionEvent < ApplicationRecord
has_many :user_actions, dependent: :restrict_with_exception
validates :details, presence: true
validates :identifier, presence: true, uniqueness: true
validates :event_type, presence: true
def self.ransackable_attributes(_auth_object = nil)
%w[identifier event_type]
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/claim_va_notification.rb
|
# frozen_string_literal: true
class ClaimVANotification < ApplicationRecord
belongs_to :saved_claim
validates :form_type, presence: true
validates :email_template_id, presence: true
validates :email_sent, inclusion: { in: [true, false] }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/veteran_onboarding.rb
|
# frozen_string_literal: true
# The VeteranOnboarding model represents the onboarding status of a veteran.
# Each instance corresponds to a veteran who is in the process of onboarding.
#
# == Schema Information
#
# Table name: veteran_onboardings
#
# id :bigint not null, primary key
# user_account_uuid :string not null, unique
# display_onboarding_flow :boolean default(TRUE)
# created_at :datetime not null
# updated_at :datetime not null
#
class VeteranOnboarding < ApplicationRecord
belongs_to :user_account, primary_key: :id, foreign_key: :user_account_uuid, inverse_of: :veteran_onboarding
validates :user_account, uniqueness: true
attr_accessor :user
# Determines whether the onboarding flow should be displayed for a veteran.
# Currently, we have two feature toggle checks:
# - veteran_onboarding_show_to_newly_onboarded examines settings for veteran_onboarding.onboarding_threshold_days,
# (default 180 days) and examines the user_verification.verified_at attribute
# - veteran_onboarding_beta_flow just checks if the feature toggle is enabled for the user
def show_onboarding_flow_on_login
if @user.user_account&.verified?
if Flipper.enabled?(:veteran_onboarding_show_to_newly_onboarded, @user)
days_since_verification = UserVerification.where(user_account_id: @user.user_account_uuid).map do |uv|
(Time.zone.today - uv.verified_at.to_date).to_i
end.max
threshold_days = Settings.veteran_onboarding&.onboarding_threshold_days || 180
if days_since_verification <= threshold_days
display_onboarding_flow
else
update!(display_onboarding_flow: false)
false
end
elsif Flipper.enabled?(:veteran_onboarding_beta_flow, @user)
display_onboarding_flow
end
end
end
def self.for_user(user)
if user.user_account&.verified? && (
Flipper.enabled?(:veteran_onboarding_beta_flow, user) ||
Flipper.enabled?(:veteran_onboarding_show_to_newly_onboarded, user)
)
veteran_onboarding = find_or_create_by(user_account: user.user_account)
veteran_onboarding.user = user
veteran_onboarding
end
end
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/user_acceptable_verified_credential.rb
|
# frozen_string_literal: true
class UserAcceptableVerifiedCredential < ApplicationRecord
belongs_to :user_account, dependent: nil, optional: false
scope :with_avc, -> { where.not(acceptable_verified_credential_at: nil) }
scope :with_ivc, -> { where.not(idme_verified_credential_at: nil) }
scope :without_avc, -> { where(acceptable_verified_credential_at: nil) }
scope :without_ivc, -> { where(idme_verified_credential_at: nil) }
scope :without_avc_ivc, -> { where(acceptable_verified_credential_at: nil, idme_verified_credential_at: nil) }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/identifier_index.rb
|
# frozen_string_literal: true
require 'common/models/base'
require 'common/models/redis_store'
class IdentifierIndex < Common::RedisStore
redis_store REDIS_CONFIG[:identifier_store][:namespace]
redis_ttl REDIS_CONFIG[:identifier_store][:each_ttl]
redis_key :identifier
attribute :identifier
attribute :email_address
validates :identifier, presence: true
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/mhv_metrics_unique_user_event.rb
|
# frozen_string_literal: true
# Unique User Metrics event tracking model for MHV Portal
#
# This model tracks unique user events for analytics purposes. Each record represents
# the first time a specific user performed a specific event (e.g., viewed MHV landing page,
# accessed secure messages, etc.).
#
# Design notes:
# - Uses compound unique index (user_id, event_name) to ensure one record per user per event
# - No foreign key constraint on user_id for performance and historical data preservation
# - Includes Redis caching to minimize database reads for duplicate event checks
class MHVMetricsUniqueUserEvent < ApplicationRecord
include RedisCaching
# Cache configuration
REDIS_CONFIG_KEY = REDIS_CONFIG[:unique_user_metrics]
CACHE_NAMESPACE = 'unique_user_metrics'
CACHE_TTL = REDIS_CONFIG_KEY[:each_ttl]
# Configure Redis caching for duplicate event checks
redis_config REDIS_CONFIG_KEY
# Active Record Validations
validates :user_id, presence: true
validates :event_name, presence: true, length: { maximum: 50 }
# Class methods for event logging and checking
# Check if a specific event has already been logged for a user
#
# @param user_id [String] UUID of the user
# @param event_name [String] Name of the event to check
# @return [Boolean] true if event exists, false otherwise
def self.event_exists?(user_id:, event_name:)
validate_inputs(user_id, event_name)
cache_key = generate_cache_key(user_id, event_name)
# Check Redis cache first for performance
return true if key_cached?(cache_key)
# Check database if not in cache
exists = exists?(user_id:, event_name:)
# Cache the result only if record exists (saves memory for non-existent records)
mark_key_cached(cache_key) if exists
exists
end
# Record a unique user event (creates record only if it doesn't exist)
#
# @param user_id [String] UUID of the user
# @param event_name [String] Name of the event to record
# @return [Boolean] true if new event was created, false if already existed
# @raise [ActiveRecord::RecordInvalid] if validation fails
def self.record_event(user_id:, event_name:)
validate_inputs(user_id, event_name)
cache_key = generate_cache_key(user_id, event_name)
# Check Redis cache first - if exists, skip database entirely
if key_cached?(cache_key)
Rails.logger.debug('UUM: Event found in cache', { user_id:, event_name: })
return false
end
# Try to insert directly using INSERT ... ON CONFLICT DO NOTHING
# This avoids raising exceptions and database error logs for duplicate records
# rubocop:disable Rails/SkipsModelValidations
# Validations are already enforced by validate_inputs above and database constraint
result = insert(
{ user_id:, event_name: },
unique_by: %i[user_id event_name],
returning: %i[user_id event_name]
)
# rubocop:enable Rails/SkipsModelValidations
# Cache that this event now exists (whether new or duplicate)
mark_key_cached(cache_key)
if result.rows.any?
Rails.logger.debug('UUM: New unique event recorded', { user_id:, event_name: })
true # NEW EVENT - top-level library should log to statsd
else
Rails.logger.debug('UUM: Duplicate event found in database', { user_id:, event_name: })
false # DUPLICATE EVENT - top-level library should NOT log to statsd
end
end
# Generate consistent cache key for user/event combination
#
# @param user_id [String] UUID of the user
# @param event_name [String] Name of the event
# @return [String] Cache key
def self.generate_cache_key(user_id, event_name)
"#{user_id}:#{event_name}"
end
# Validate input parameters
#
# @param user_id [String] UUID of the user
# @param event_name [String] Name of the event
# @raise [ArgumentError] if inputs are invalid
def self.validate_inputs(user_id, event_name)
raise ArgumentError, 'user_id is required' if user_id.blank?
raise ArgumentError, 'event_name is required' if event_name.blank?
raise ArgumentError, 'event_name must be 50 characters or less' if event_name.length > 50
end
# Check if a cache key exists (presence-based caching)
#
# @param key [String] Cache key to check
# @return [Boolean] true if key exists in cache, false otherwise
def self.key_cached?(key)
Rails.cache.exist?(key, namespace: CACHE_NAMESPACE)
end
# Mark a cache key as existing (sets key to indicate presence)
#
# @param key [String] Cache key to mark as cached
def self.mark_key_cached(key)
Rails.cache.write(key, true, namespace: CACHE_NAMESPACE, expires_in: CACHE_TTL)
end
private_class_method :generate_cache_key, :validate_inputs, :key_cached?, :mark_key_cached
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/terms_of_use_agreement.rb
|
# frozen_string_literal: true
class TermsOfUseAgreement < ApplicationRecord
CURRENT_VERSION = IdentitySettings.terms_of_use.current_version
belongs_to :user_account
validates :agreement_version, :response, presence: true
enum :response, { declined: 0, accepted: 1 }
default_scope { order(created_at: :asc) }
scope :current, -> { where(agreement_version: CURRENT_VERSION) }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/id_card_announcement_subscription.rb
|
# frozen_string_literal: true
class IdCardAnnouncementSubscription < ApplicationRecord
validates :email,
uniqueness: true,
length: { maximum: 255 },
format: { with: /\A[^@\s]+@([^@\s]+\.)+[^@\s]+\z/ } # Devise::email_regexp
scope :va, -> { where("split_part(email, '@', 2) = 'va.gov'") }
scope :non_va, -> { where("split_part(email, '@', 2) <> 'va.gov'") }
end
|
0
|
code_files/vets-api-private/app
|
code_files/vets-api-private/app/models/average_days_for_claim_completion.rb
|
# frozen_string_literal: true
class AverageDaysForClaimCompletion < ApplicationRecord
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.