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/sidekiq
|
code_files/vets-api-private/app/sidekiq/bgs/job.rb
|
# frozen_string_literal: true
require 'bgs/utilities/helpers'
module BGS
class Job
include BGS::Utilities::Helpers
FILTERED_ERRORS = [
'insertBenefitClaim: Invalid zipcode.',
'Maximum number of EPs reached for this bnftClaimTypeCd',
'This update is being elevated for additional review due to an Incident Flash associated with this Beneficiary',
'ORA-20099: Error - File Number and Social Security number are different',
'ORA-00001: unique constraint',
'The length of the EXTERNAL_UID or EXTERNAL_KEY exceeds the maximum'
].freeze
def in_progress_form_copy(in_progress_form)
return nil if in_progress_form.blank?
OpenStruct.new(meta_data: in_progress_form.metadata,
form_data: in_progress_form.form_data,
user_account: in_progress_form.user_account)
end
def salvage_save_in_progress_form(form_id, user_uuid, copy)
return if copy.blank?
form = InProgressForm.where(form_id:, user_uuid:).first_or_initialize
form.user_account = copy.user_account
form.update(form_data: copy.form_data)
end
# BGS doesn't accept name and address_line fields with non-ASCII characters (e.g. ü, ñ), and doesn't accept names
# with apostrophes. This method recursively iterates through a given hash and strips unprocessable characters
# from name and address_line fields. The method is called in `SubmitForm686cJob` and `SubmitForm674Job` with an
# enormous form payload potentially containing many names and addresses.
# See `spec/factories/686c/form_686c_674.rb` for an example of such a payload.
def normalize_names_and_addresses!(hash)
hash.each do |key, val|
case val
when Hash
normalize_names_and_addresses!(val)
when Array
val.each { |v| normalize_names_and_addresses!(v) if v.is_a?(Hash) }
else
is_name_key = %w[first middle last].include?(key)
if val && (is_name_key || key.include?('address_line') || key.include?('street'))
val = normalize_composite_characters(val)
val = remove_special_characters_from_name(val) if is_name_key
hash[key] = val
end
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/bgs/submit_form686c_job.rb
|
# frozen_string_literal: true
require 'bgs/form686c'
require 'dependents/monitor'
require 'vets/shared_logging'
module BGS
class SubmitForm686cJob < Job
class Invalid686cClaim < StandardError; end
FORM_ID = '686C-674'
include Sidekiq::Job
include Vets::SharedLogging
attr_reader :claim, :user, :user_uuid, :saved_claim_id, :vet_info, :icn
STATS_KEY = 'worker.submit_686c_bgs'
# retry for 2d 1h 47m 12s
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
sidekiq_options retry: 16
sidekiq_retries_exhausted do |msg, _error|
user_uuid, saved_claim_id, encrypted_vet_info = msg['args']
vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info))
monitor = ::Dependents::Monitor.new(saved_claim_id)
monitor.track_event('error',
"BGS::SubmitForm686cJob failed, retries exhausted! Last error: #{msg['error_message']}",
'worker.submit_686c_bgs.exhaustion')
BGS::SubmitForm686cJob.send_backup_submission(vet_info, saved_claim_id, user_uuid)
end
# method length lint disabled because this will be cut in half when flipper is removed
def perform(user_uuid, saved_claim_id, encrypted_vet_info)
@monitor = init_monitor(saved_claim_id)
@monitor.track_event('info', 'BGS::SubmitForm686cJob running!', "#{STATS_KEY}.begin")
instance_params(encrypted_vet_info, user_uuid, saved_claim_id)
submit_686c
@monitor.track_event('info', 'BGS::SubmitForm686cJob succeeded!', "#{STATS_KEY}.success")
if claim.submittable_674?
enqueue_674_job(encrypted_vet_info)
else
# if no 674, form submission is complete
send_686c_confirmation_email
InProgressForm.destroy_by(form_id: FORM_ID, user_uuid:)
end
rescue => e
handle_filtered_errors!(e:, encrypted_vet_info:)
@monitor.track_event('warn', 'BGS::SubmitForm686cJob received error, retrying...', "#{STATS_KEY}.failure",
{ error: e.message, nested_error: e.cause&.message })
raise
end
def handle_filtered_errors!(e:, encrypted_vet_info:)
filter = FILTERED_ERRORS.any? { |filtered| e.message.include?(filtered) || e.cause&.message&.include?(filtered) }
return unless filter
@monitor.track_event('warn', 'BGS::SubmitForm686cJob received error, skipping retries...',
"#{STATS_KEY}.skip_retries", { error: e.message, nested_error: e.cause&.message })
vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info))
self.class.send_backup_submission(vet_info, saved_claim_id, user_uuid)
raise Sidekiq::JobRetry::Skip
end
def instance_params(encrypted_vet_info, user_uuid, saved_claim_id)
@vet_info = JSON.parse(KmsEncrypted::Box.new.decrypt(encrypted_vet_info))
@user = BGS::SubmitForm686cJob.generate_user_struct(@vet_info)
@icn = @user.icn
@user_uuid = user_uuid
@saved_claim_id = saved_claim_id
@claim ||= SavedClaim::DependencyClaim.find(saved_claim_id)
end
def self.generate_user_struct(vet_info)
info = vet_info['veteran_information']
full_name = info['full_name']
OpenStruct.new(
first_name: full_name['first'],
last_name: full_name['last'],
middle_name: full_name['middle'],
ssn: info['ssn'],
email: info['email'],
va_profile_email: info['va_profile_email'],
participant_id: info['participant_id'],
icn: info['icn'],
uuid: info['uuid'],
common_name: info['common_name']
)
end
def self.send_backup_submission(vet_info, saved_claim_id, user_uuid)
user = generate_user_struct(vet_info)
Lighthouse::BenefitsIntake::SubmitCentralForm686cJob.perform_async(
saved_claim_id,
KmsEncrypted::Box.new.encrypt(vet_info.to_json),
KmsEncrypted::Box.new.encrypt(user.to_h.to_json)
)
InProgressForm.destroy_by(form_id: FORM_ID, user_uuid:)
rescue => e
monitor = ::Dependents::Monitor.new(saved_claim_id)
monitor.track_event('error', 'BGS::SubmitForm686cJob backup submission failed...',
"#{STATS_KEY}.backup_failure", { error: e.message, nested_error: e.cause&.message })
InProgressForm.find_by(form_id: FORM_ID, user_uuid:)&.submission_pending!
end
private
def submit_forms(encrypted_vet_info)
claim.add_veteran_info(vet_info)
raise Invalid686cClaim unless claim.valid?(:run_686_form_jobs)
claim_data = normalize_names_and_addresses!(claim.formatted_686_data(vet_info))
BGS::Form686c.new(user, claim).submit(claim_data)
# If Form 686c job succeeds, then enqueue 674 job.
BGS::SubmitForm674Job.perform_async(user_uuid, saved_claim_id, encrypted_vet_info, KmsEncrypted::Box.new.encrypt(user.to_h.to_json)) if claim.submittable_674? # rubocop:disable Layout/LineLength
end
def submit_686c
claim.add_veteran_info(vet_info)
raise Invalid686cClaim unless claim.valid?(:run_686_form_jobs)
claim_data = normalize_names_and_addresses!(claim.formatted_686_data(vet_info))
BGS::Form686c.new(user, claim).submit(claim_data)
end
def enqueue_674_job(encrypted_vet_info)
BGS::SubmitForm674Job.perform_async(user_uuid, saved_claim_id, encrypted_vet_info,
KmsEncrypted::Box.new.encrypt(user.to_h.to_json))
end
def send_686c_confirmation_email
claim.send_received_email(user)
end
def send_confirmation_email
return if user.va_profile_email.blank?
VANotify::ConfirmationEmail.send(
email_address: user.va_profile_email,
template_id: Settings.vanotify.services.va_gov.template_id.form686c_confirmation_email,
first_name: user&.first_name&.upcase,
user_uuid_and_form_id: "#{user.uuid}_#{FORM_ID}"
)
end
def init_monitor(saved_claim_id)
@monitor ||= ::Dependents::Monitor.new(saved_claim_id)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/dependents/form_686c_674_failure_email_job.rb
|
# frozen_string_literal: true
require 'va_notify/service'
require 'dependents/monitor'
class Dependents::Form686c674FailureEmailJob
include Sidekiq::Job
FORM_ID = '686C-674'
FORM_ID_674 = '21-674'
STATSD_KEY_PREFIX = 'api.dependents.form_686c_674_failure_email_job'
ZSF_DD_TAG_FUNCTION = '686c_674_failure_email_queuing'
sidekiq_options retry: 16
sidekiq_retries_exhausted do |msg, ex|
claim_id = msg['args'].first
Rails.logger.error('Form686c674FailureEmailJob exhausted all retries',
{
saved_claim_id: claim_id,
error_message: ex.message
})
monitor = Dependents::Monitor.new(claim_id)
monitor.log_silent_failure(monitor.default_payload.merge(message: ex.message),
call_location: caller_locations.first)
end
def perform(claim_id, email, template_id, personalisation)
@claim = SavedClaim::DependencyClaim.find(claim_id)
@monitor = init_monitor(claim_id)
va_notify_client.send_email(email_address: email,
template_id:,
personalisation:)
@monitor.log_silent_failure_avoided(@monitor.default_payload, call_location: caller_locations.first)
rescue => e
Rails.logger.warn('Form686c674FailureEmailJob failed, retrying send...', { claim_id:, error: e })
raise e
end
private
def va_notify_client
@va_notify_client ||= VaNotify::Service.new(Settings.vanotify.services.va_gov.api_key, callback_options)
end
def callback_options
{
callback_metadata: {
notification_type: 'error',
form_id: @claim.form_id,
statsd_tags: { service: 'dependent-change', function: ZSF_DD_TAG_FUNCTION }
}
}
end
def init_monitor(saved_claim_id)
@monitor ||= Dependents::Monitor.new(saved_claim_id)
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/preneeds/delete_old_uploads.rb
|
# frozen_string_literal: true
module Preneeds
class DeleteOldUploads < DeleteAttachmentJob
ATTACHMENT_CLASSES = %w[Preneeds::PreneedAttachment].freeze
FORM_ID = '40-10007'
def get_uuids(form_data)
uuids = []
Array.wrap(form_data['preneedAttachments']).each do |attachment|
uuids << attachment['confirmationCode']
end
uuids
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/simple_forms_api
|
code_files/vets-api-private/app/sidekiq/simple_forms_api/notification/send_notification_email_job.rb
|
# frozen_string_literal: true
module SimpleFormsApi
module Notification
class SendNotificationEmailJob
include Sidekiq::Job
sidekiq_options retry: 10, backtrace: true
HOUR_TO_SEND_NOTIFICATIONS = 9
def perform(benefits_intake_uuid, form_number)
@benefits_intake_uuid = benefits_intake_uuid
@form_number = form_number
@user_account = form_submission_attempt.user_account
@form_submission = form_submission_attempt.form_submission
return unless valid_notification?
send_email
rescue => e
handle_exception(e)
end
private
attr_accessor :user_account, :form_number, :form_submission
def valid_notification?
form_submission_attempt.failure? || form_submission_attempt.vbms?
end
def notification_type
if form_submission_attempt.failure?
:error
elsif form_submission_attempt.vbms?
:received
end
end
def form_submission_attempt
@form_submission_attempt ||= FormSubmissionAttempt.find_by(benefits_intake_uuid: @benefits_intake_uuid) ||
raise_not_found_error('FormSubmissionAttempt', @benefits_intake_uuid)
end
def raise_not_found_error(resource, id)
raise ActiveRecord::RecordNotFound, "#{resource} #{id} not found"
end
def config
{
form_data: JSON.parse(form_submission.form_data.presence || '{}'),
form_number:,
confirmation_number: @benefits_intake_uuid,
date_submitted: form_submission_attempt.created_at.strftime('%B %d, %Y'),
lighthouse_updated_at: form_submission_attempt.lighthouse_updated_at&.strftime('%B %d, %Y')
}
end
def form_upload_supported?
SimpleFormsApi::Notification::FormUploadEmail::SUPPORTED_FORMS.include?(form_number)
end
def form_upload_notification_email
SimpleFormsApi::Notification::FormUploadEmail.new(config, notification_type:)
end
def notification_email
SimpleFormsApi::Notification::Email.new(
config,
notification_type:,
user_account:
)
end
def time_to_send
now = Time.zone.now.in_time_zone('Eastern Time (US & Canada)')
target_time = now.change(hour: HOUR_TO_SEND_NOTIFICATIONS, min: 0)
now.hour < HOUR_TO_SEND_NOTIFICATIONS ? target_time : target_time.tomorrow
end
def send_email
email = form_upload_supported? ? form_upload_notification_email : notification_email
email.send(at: time_to_send)
end
def statsd_tags
{ 'service' => 'veteran-facing-forms', 'function' => "#{form_number} form submission to Lighthouse" }
end
def handle_exception(e)
Rails.logger.error(
'Error sending simple forms notification email',
message: e.message,
notification_type:,
confirmation_number: config&.dig(:confirmation_number)
)
StatsD.increment('silent_failure', tags: statsd_tags) if notification_type == :error
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/simple_forms_api
|
code_files/vets-api-private/app/sidekiq/simple_forms_api/form_remediation/upload_retry_job.rb
|
# frozen_string_literal: true
module SimpleFormsApi
module FormRemediation
class UploadRetryJob
include Sidekiq::Job
sidekiq_options retry: 10
STATSD_KEY_PREFIX = 'api.simple_forms_api.upload_retry_job'
sidekiq_retries_exhausted do |_msg, ex|
StatsD.increment("#{STATSD_KEY_PREFIX}.retries_exhausted")
Rails.logger.error(
'SimpleFormsApi::FormRemediation::UploadRetryJob retries exhausted',
{ exception: "#{ex.class} - #{ex.message}", backtrace: ex.backtrace&.join("\n").to_s }
)
end
def perform(file, directory, config)
@file = file
@directory = directory
@config = config
uploader = config.uploader_class.new(directory:, config:)
begin
StatsD.increment("#{STATSD_KEY_PREFIX}.total")
uploader.store!(file)
rescue Aws::S3::Errors::ServiceError
raise if service_available?(config.s3_settings.region)
retry_later
end
end
private
attr_accessor :file, :directory, :config
def service_available?(region)
Aws::S3::Client.new(region:).list_buckets
true
rescue Aws::S3::Errors::ServiceError
false
end
def retry_later(delay: 30.minutes.from_now)
Rails.logger.info("S3 service unavailable. Retrying upload later for #{file.filename}.")
self.class.perform_in(delay, file, directory, config)
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/unified_health_data/facility_name_cache_job.rb
|
# frozen_string_literal: true
require 'lighthouse/facilities/v1/client'
module UnifiedHealthData
# FacilityNameCacheJob
#
# This Sidekiq job fetches VHA facilities from the Lighthouse Facilities API
# and caches a mapping of station_number -> facility_name in Rails cache.
# The cache is set to expire after 4 hours to ensure fresh data with hourly refreshes.
#
# Why:
# - Prescription processing needs facility names for station numbers from Oracle Health
# - Making individual API calls per prescription is inefficient and can hit rate limits
# - HealthFacility table excludes some facilities that VHA includes
# - Rails cache provides fast lookups with automatic expiration
#
# How:
# - Fetches all VHA facilities from Lighthouse API
# - Extracts station numbers from facility IDs (removes 'vha_' prefix)
# - Stores station_number -> facility_name mapping in Rails cache
# - Sets 4-hour TTL with hourly refresh for reliability
#
class FacilityNameCacheJob
include Sidekiq::Job
CACHE_KEY_PREFIX = 'uhd:facility_names'
BATCH_SIZE = 1000
# retry for ~30 minutes max since job runs every hour
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
sidekiq_options retry: 3
sidekiq_retries_exhausted do |msg|
Rails.logger.error("[UnifiedHealthData] - #{msg['class']} failed with no retries left: #{msg['error_message']}")
StatsD.increment('unified_health_data.facility_name_cache_job.failed_no_retries')
end
def perform
facility_map = fetch_vha_facilities
cache_facility_names(facility_map)
Rails.logger.info("[UnifiedHealthData] - Cached #{facility_map.size} VHA facility names")
StatsD.increment('unified_health_data.facility_name_cache_job.complete')
StatsD.gauge('unified_health_data.facility_name_cache_job.facilities_cached', facility_map.size)
rescue => e
Rails.logger.error("[UnifiedHealthData] - Error in #{self.class.name}: #{e.message}")
StatsD.increment('unified_health_data.facility_name_cache_job.error')
raise "Failed to cache facility names: #{e.message}"
end
private
def fetch_vha_facilities
facilities_client = Lighthouse::Facilities::V1::Client.new
all_facilities = []
Rails.logger.info('[UnifiedHealthData] - Fetching VHA facilities from Lighthouse API')
response = facilities_client.get_paginated_facilities(
type: 'health',
per_page: BATCH_SIZE,
page: 1
)
loop do
all_facilities.concat(extract_vha_facilities(response))
# Check if there's a next page link
break unless response.links&.dig('next')
response = fetch_next_page(facilities_client, response.links['next'])
end
# Convert to hash for easy lookup
all_facilities.to_h { |facility| [facility[:station_number], facility[:name]] }
end
def extract_vha_facilities(response)
response.facilities.filter_map do |facility|
next unless facility.id.start_with?('vha_')
station_number = facility.id.sub(/^vha_/, '')
{ station_number:, name: facility.name }
end
end
def fetch_next_page(client, next_url)
next_url = URI.parse(next_url)
next_params = URI.decode_www_form(next_url.query).to_h.transform_keys(&:to_sym)
client.get_paginated_facilities(next_params)
end
def cache_facility_names(facility_map)
return if facility_map.empty?
Rails.logger.info('[UnifiedHealthData] - Caching facility names for 4 hours')
# Cache current facility names using Rails cache
facility_map.each do |station_number, facility_name|
cache_key = "#{CACHE_KEY_PREFIX}:#{station_number}"
Rails.cache.write(cache_key, facility_name, expires_in: 4.hours)
end
Rails.logger.info("[UnifiedHealthData] - Cache operation complete: #{facility_map.size} facilities cached")
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/unified_health_data/labs_refresh_job.rb
|
# frozen_string_literal: true
require 'unified_health_data/service'
##
# Background job to load lab data from the Unified Health Data service
#
module UnifiedHealthData
class LabsRefreshJob
include Sidekiq::Job
sidekiq_options retry: 0, unique_for: 30.minutes
def perform(user_uuid)
user = find_user(user_uuid)
return unless user
start_date, end_date = date_range
labs_data = fetch_labs_data(user, start_date, end_date)
log_success(labs_data, start_date, end_date)
StatsD.gauge('unified_health_data.labs_refresh_job.labs_count', labs_data.size)
labs_data.size
rescue => e
log_error(e)
raise
end
private
def find_user(user_uuid)
user = User.find(user_uuid)
return user if user
Rails.logger.error("UHD Labs Refresh Job: User not found for UUID: #{user_uuid}")
nil
end
def date_range
end_date = Date.current
days_back = Settings.mhv.uhd.labs_logging_date_range_days.to_i
start_date = end_date - days_back.days
[start_date, end_date]
end
def fetch_labs_data(user, start_date, end_date)
uhd_service = UnifiedHealthData::Service.new(user)
uhd_service.get_labs(
start_date: start_date.strftime('%Y-%m-%d'),
end_date: end_date.strftime('%Y-%m-%d')
)
end
def log_success(labs_data, start_date, end_date)
Rails.logger.info(
'UHD Labs Refresh Job completed successfully',
records_count: labs_data.size,
start_date: start_date.strftime('%Y-%m-%d'),
end_date: end_date.strftime('%Y-%m-%d')
)
end
def log_error(error)
Rails.logger.error(
'UHD Labs Refresh Job failed',
error: error.message
)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/evss/delete_old_claims.rb
|
# frozen_string_literal: true
module EVSS
class DeleteOldClaims
include Sidekiq::Job
sidekiq_options queue: 'low'
def perform
Sentry.set_tags(source: 'claims-status')
claims = EVSSClaim.where('updated_at < ?', 1.day.ago)
logger.info("Deleting #{claims.count} old EVSS claims")
claims.delete_all
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/evss/failure_notification.rb
|
# frozen_string_literal: true
require 'vets/shared_logging'
class EVSS::FailureNotification
include Sidekiq::Job
include Vets::SharedLogging
NOTIFY_SETTINGS = Settings.vanotify.services.benefits_management_tools
MAILER_TEMPLATE_ID = NOTIFY_SETTINGS.template_id.evidence_submission_failure_email
# retry for one day
sidekiq_options retry: 14, queue: 'low'
# Set minimum retry time to ~1 hour
sidekiq_retry_in do |count, _exception|
rand(3600..3660) if count < 9
end
sidekiq_retries_exhausted do
::Rails.logger.info('EVSS::FailureNotification email could not be sent')
end
def notify_client
VaNotify::Service.new(NOTIFY_SETTINGS.api_key, { callback_klass: 'BenefitsDocuments::VANotifyEmailStatusCallback' })
end
def perform(icn, personalisation)
# NOTE: The file_name in the personalisation that is passed in is obscured
notify_client.send_email(
recipient_identifier: { id_value: icn, id_type: 'ICN' },
template_id: MAILER_TEMPLATE_ID,
personalisation:
)
::Rails.logger.info('EVSS::FailureNotification email sent')
rescue => e
::Rails.logger.error('EVSS::FailureNotification email error',
{ message: e.message })
log_exception_to_sentry(e)
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/evss/request_decision.rb
|
# frozen_string_literal: true
class EVSS::RequestDecision
include Sidekiq::Job
# retry for 2d 1h 47m 12s
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
sidekiq_options retry: 16
def perform(auth_headers, evss_id)
client = EVSS::ClaimsService.new(auth_headers)
client.request_decision(evss_id)
end
end
# Allows gracefully migrating tasks in queue
# TODO(knkski): Remove after migration
class EVSSClaim::RequestDecision
include Sidekiq::Job
def perform(auth_headers, evss_id)
EVSS::RequestDecision.perform_async(auth_headers, evss_id)
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/evss/document_upload.rb
|
# frozen_string_literal: true
require 'datadog'
require 'timeout'
require 'logging/third_party_transaction'
require 'evss/failure_notification'
require 'lighthouse/benefits_documents/constants'
require 'lighthouse/benefits_documents/utilities/helpers'
require 'vets/shared_logging'
class EVSS::DocumentUpload
include Sidekiq::Job
extend Vets::SharedLogging
extend Logging::ThirdPartyTransaction::MethodWrapper
DD_ZSF_TAGS = ['service:claim-status', 'function: evidence upload to EVSS'].freeze
attr_accessor :auth_headers, :user_uuid, :document_hash
wrap_with_logging(
:pull_file_from_cloud!,
:perform_initial_file_read,
:perform_document_upload_to_evss,
:clean_up!,
additional_class_logs: {
form: 'Benefits Document Upload to EVSS API',
upstream: "S3 bucket: #{Settings.evss.s3.bucket}",
downstream: "EVSS API: #{EVSS::DocumentsService::BASE_URL}"
}
)
# retry for one day
sidekiq_options retry: 16, queue: 'low'
# Set minimum retry time to ~1 hour
sidekiq_retry_in do |count, _exception|
rand(3600..3660) if count < 9
end
sidekiq_retries_exhausted do |msg, _ex|
verify_msg(msg)
# Grab the evidence_submission_id from the msg args
evidence_submission = EvidenceSubmission.find_by(id: msg['args'][3])
if can_update_evidence_submission(evidence_submission)
update_evidence_submission_for_failure(evidence_submission, msg)
else
call_failure_notification(msg)
end
end
def perform(auth_headers, user_uuid, document_hash, evidence_submission_id = nil)
@auth_headers = auth_headers
@user_uuid = user_uuid
@document_hash = document_hash
validate_document!
pull_file_from_cloud!
evidence_submission = EvidenceSubmission.find_by(id: evidence_submission_id)
if self.class.can_update_evidence_submission(evidence_submission)
update_evidence_submission_with_job_details(evidence_submission)
end
perform_document_upload_to_evss
if self.class.can_update_evidence_submission(evidence_submission)
update_evidence_submission_for_success(evidence_submission)
end
clean_up!
end
def self.verify_msg(msg)
raise StandardError, "Missing fields in #{name}" if invalid_msg_fields?(msg) || invalid_msg_args?(msg['args'])
end
def self.invalid_msg_fields?(msg)
!(%w[jid args created_at failed_at] - msg.keys).empty?
end
def self.invalid_msg_args?(args)
return true unless args[0].is_a?(Hash)
return true unless args[2].is_a?(Hash)
return true if args[0]['va_eauth_firstName'].empty?
!(%w[evss_claim_id tracked_item_id document_type file_name] - args[2].keys).empty?
end
def self.update_evidence_submission_for_failure(evidence_submission, msg)
current_personalisation = JSON.parse(evidence_submission.template_metadata)['personalisation']
evidence_submission.update!(
upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:FAILED],
failed_date: DateTime.current,
acknowledgement_date: (DateTime.current + 30.days),
error_message: 'EVSS::DocumentUpload document upload failure',
template_metadata: {
personalisation: update_personalisation(current_personalisation, msg['failed_at'])
}.to_json
)
add_log('FAILED', evidence_submission.claim_id, evidence_submission.id, msg['jid'])
message = "#{name} EvidenceSubmission updated"
StatsD.increment('silent_failure_avoided_no_confirmation',
tags: ['service:claim-status', "function: #{message}"])
rescue => e
error_message = "#{name} failed to update EvidenceSubmission"
::Rails.logger.error(error_message, { message: e.message })
StatsD.increment('silent_failure', tags: ['service:claim-status', "function: #{error_message}"])
end
def self.call_failure_notification(msg)
return unless Flipper.enabled?(:cst_send_evidence_failure_emails)
icn = UserAccount.find(msg['args'][1]).icn
EVSS::FailureNotification.perform_async(icn, create_personalisation(msg))
::Rails.logger.info('EVSS::DocumentUpload exhaustion handler email queued')
StatsD.increment('silent_failure_avoided_no_confirmation', tags: DD_ZSF_TAGS)
rescue => e
::Rails.logger.error('EVSS::DocumentUpload exhaustion handler email error',
{ message: e.message })
StatsD.increment('silent_failure', tags: DD_ZSF_TAGS)
log_exception_to_sentry(e)
log_exception_to_rails(e)
end
# Update personalisation here since an evidence submission record was previously created
def self.update_personalisation(current_personalisation, failed_at)
personalisation = current_personalisation.clone
personalisation['date_failed'] = helpers.format_date_for_mailers(failed_at)
personalisation
end
# This will be used by EVSS::FailureNotification
def self.create_personalisation(msg)
first_name = msg['args'][0]['va_eauth_firstName'].titleize unless msg['args'][0]['va_eauth_firstName'].nil?
document_type = EVSSClaimDocument.new(msg['args'][2]).description
# Obscure the file name here since this will be used to generate a failed email
# NOTE: the template that we use for va_notify.send_email uses `filename` but we can also pass in `file_name`
filename = helpers.generate_obscured_file_name(msg['args'][2]['file_name'])
date_submitted = helpers.format_date_for_mailers(msg['created_at'])
date_failed = helpers.format_date_for_mailers(msg['failed_at'])
{ first_name:, document_type:, filename:, date_submitted:, date_failed: }
end
def self.helpers
BenefitsDocuments::Utilities::Helpers
end
def self.add_log(type, claim_id, evidence_submission_id, job_id)
::Rails.logger.info("EVSS - Updated Evidence Submission Record to #{type}", {
claim_id:,
evidence_submission_id:,
job_id:
})
end
def self.can_update_evidence_submission(evidence_submission)
Flipper.enabled?(:cst_send_evidence_submission_failure_emails) && !evidence_submission.nil?
end
private
def validate_document!
Sentry.set_tags(source: 'claims-status')
raise Common::Exceptions::ValidationErrors unless document.valid?
end
def pull_file_from_cloud!
uploader.retrieve_from_store!(document.file_name)
end
def perform_document_upload_to_evss
Rails.logger.info('Begining document upload file to EVSS', filesize: file_body.try(:size))
client.upload(file_body, document)
end
def clean_up!
uploader.remove!
end
def perform_initial_file_read
uploader.read_for_upload
end
def uploader
@uploader ||= EVSSClaimDocumentUploader.new(user_uuid, document.uploader_ids)
end
def document
@document ||= EVSSClaimDocument.new(document_hash)
end
def client
@client ||= EVSS::DocumentsService.new(auth_headers)
end
def file_body
@file_body ||= perform_initial_file_read
end
def update_evidence_submission_with_job_details(evidence_submission)
evidence_submission.update!(
upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:QUEUED],
job_id: jid,
job_class: self.class
)
StatsD.increment('cst.evss.document_uploads.evidence_submission_record_updated.queued')
self.class.add_log('QUEUED', evidence_submission.claim_id, evidence_submission.id, jid)
end
def update_evidence_submission_for_success(evidence_submission)
evidence_submission.update!(
upload_status: BenefitsDocuments::Constants::UPLOAD_STATUS[:SUCCESS],
delete_date: (DateTime.current + 60.days)
)
StatsD.increment('cst.evss.document_uploads.evidence_submission_record_updated.success')
self.class.add_log('SUCCESS', evidence_submission.claim_id, evidence_submission.id, jid)
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/submit_form0781.rb
|
# frozen_string_literal: true
require 'pdf_utilities/datestamp_pdf'
require 'pdf_fill/filler'
require 'logging/call_location'
require 'logging/third_party_transaction'
require 'zero_silent_failures/monitor'
module EVSS
module DisabilityCompensationForm
class SubmitForm0781 < Job
ZSF_DD_TAG_FUNCTION = '526_form_0781_failure_email_queuing'
extend Logging::ThirdPartyTransaction::MethodWrapper
attr_reader :submission_id, :evss_claim_id, :uuid
wrap_with_logging(
:upload_to_vbms,
:perform_client_upload,
additional_class_logs: {
action: 'upload form 21-0781'
},
additional_instance_logs: {
submission_id: [:submission_id],
evss_claim_id: [:evss_claim_id],
uuid: [:uuid]
}
)
FORM_ID_0781 = '21-0781' # form id for PTSD
FORM_ID_0781A = '21-0781a' # form id for PTSD Secondary to Personal Assault
FORM_ID_0781V2 = '21-0781V2' # form id for Mental Health Disorder(s) Due to In-Service Traumatic Event(s)
FORMS_METADATA = {
FORM_ID_0781 => { docType: 'L228' },
FORM_ID_0781A => { docType: 'L229' },
FORM_ID_0781V2 => { docType: 'L228' }
}.freeze
STATSD_KEY_PREFIX = 'worker.evss.submit_form0781'
# Sidekiq has built in exponential back-off functionality for retries
# A max retry attempt of 16 will result in a run time of ~48 hours
# This job is invoked from 526 background job
RETRY = 16
sidekiq_options retry: RETRY
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
form526_submission_id = msg['args'].first
log_info = { job_id:, error_class:, error_message:, timestamp:, form526_submission_id: }
::Rails.logger.warn('Submit Form 0781 Retries exhausted', log_info)
form_job_status = Form526JobStatus.find_by(job_id:)
bgjob_errors = form_job_status.bgjob_errors || {}
new_error = {
"#{timestamp.to_i}": {
caller_method: __method__.to_s,
error_class:,
error_message:,
timestamp:,
form526_submission_id:
}
}
form_job_status.update(
status: Form526JobStatus::STATUS[:exhausted],
bgjob_errors: bgjob_errors.merge(new_error)
)
if Flipper.enabled?(:disability_compensation_use_api_provider_for_0781_uploads)
submission = Form526Submission.find(form526_submission_id)
provider = api_upload_provider(submission, FORM_ID_0781)
provider.log_uploading_job_failure(self, error_class, error_message)
end
StatsD.increment("#{STATSD_KEY_PREFIX}.exhausted")
if Flipper.enabled?(:form526_send_0781_failure_notification)
EVSS::DisabilityCompensationForm::Form0781DocumentUploadFailureEmail.perform_async(form526_submission_id)
end
# NOTE: do NOT add any additional code here between the failure email being enqueued and the rescue block.
# The mailer prevents an upload from failing silently, since we notify the veteran and provide a workaround.
# The rescue will catch any errors in the sidekiq_retries_exhausted block and mark a "silent failure".
# This shouldn't happen if an email was sent; there should be no code here to throw an additional exception.
# The mailer should be the last thing that can fail.
rescue => e
cl = caller_locations.first
call_location = Logging::CallLocation.new(ZSF_DD_TAG_FUNCTION, cl.path, cl.lineno)
zsf_monitor = ZeroSilentFailures::Monitor.new(Form526Submission::ZSF_DD_TAG_SERVICE)
user_account_id = begin
Form526Submission.find(form526_submission_id).user_account_id
rescue
nil
end
zsf_monitor.log_silent_failure(log_info, user_account_id, call_location:)
::Rails.logger.error(
'Failure in SubmitForm0781#sidekiq_retries_exhausted',
{
messaged_content: e.message,
job_id:,
submission_id: form526_submission_id,
pre_exhaustion_failure: {
error_class:,
error_message:
}
}
)
raise e
end
def self.api_upload_provider(submission, form_id)
user = User.find(submission.user_uuid)
ApiProviderFactory.call(
type: ApiProviderFactory::FACTORIES[:supplemental_document_upload],
options: {
form526_submission: submission,
document_type: FORMS_METADATA[form_id][:docType],
statsd_metric_prefix: STATSD_KEY_PREFIX
},
current_user: user,
feature_toggle: ApiProviderFactory::FEATURE_TOGGLE_UPLOAD_0781
)
end
# This method generates the PDF documents but does NOT send them anywhere.
# It just generates them to the filesystem and returns the path to them to be used by other methods.
#
# @param submission_id [Integer] The {Form526Submission} id
# @param uuid [String] The Central Mail UUID, not actually used,
# but is passed along as the existing process_0781 function requires something here
# @return [Hash] Returns a hash with the keys
# `type` (to discern between if it is a 0781 or 0781a form) and
# `file`, which is the generated file location
def get_docs(submission_id, uuid)
@submission_id = submission_id
@uuid = uuid
@submission = Form526Submission.find_by(id: submission_id)
file_type_and_file_objs = []
{
'form0781' => FORM_ID_0781,
'form0781a' => FORM_ID_0781A,
'form0781v2' => FORM_ID_0781V2
}.each do |form_type_key, actual_form_types|
form_content = parsed_forms[form_type_key]
if form_content.present?
file_type_and_file_objs << {
type: actual_form_types,
file: process_0781(uuid, actual_form_types, form_content, upload: false)
}
end
end
file_type_and_file_objs
end
def parsed_forms
@parsed_forms ||= JSON.parse(submission.form_to_json(Form526Submission::FORM_0781))
end
# Performs an asynchronous job for generating and submitting 0781 + 0781A PDF documents to VBMS
#
# @param submission_id [Integer] The {Form526Submission} id
#
def perform(submission_id)
@submission_id = submission_id
Sentry.set_tags(source: '526EZ-all-claims')
super(submission_id)
with_tracking('Form0781 Submission', submission.saved_claim_id, submission.id) do
# process 0781, 0781a and 0781v2
{
'form0781' => FORM_ID_0781,
'form0781a' => FORM_ID_0781A,
'form0781v2' => FORM_ID_0781V2
}.each do |form_key, form_id|
form_content = parsed_forms[form_key]
if form_content.present?
submitted_claim_id = submission.submitted_claim_id
::Rails.logger.info('Performing SubmitForm0781', { submission_id:, form_id:, submitted_claim_id: })
process_0781(submitted_claim_id, form_id, form_content)
end
end
end
rescue => e
# Cannot move job straight to dead queue dynamically within an executing job
# raising error for all the exceptions as sidekiq will then move into dead queue
# after all retries are exhausted
retryable_error_handler(e)
raise e
end
private
def process_0781(evss_claim_id, form_id, form_content, upload: true)
@evss_claim_id = evss_claim_id
# generate and stamp PDF file
pdf_path0781 = generate_stamp_pdf(form_content, evss_claim_id, form_id)
upload ? upload_to_vbms(pdf_path0781, form_id) : pdf_path0781
end
# Invokes Filler ancillary form method to generate PDF document
# Then calls method PDFUtilities::DatestampPdf to stamp the document.
# Its called twice, once to stamp with text "VA.gov YYYY-MM-DD" at the bottom of each page
# and second time to stamp with text "VA.gov Submission" at the top of each page
def generate_stamp_pdf(form_content, evss_claim_id, form_id)
submission_date = @submission&.created_at&.in_time_zone('Central Time (US & Canada)')
form_content = form_content.merge({ 'signatureDate' => submission_date })
user = OpenStruct.new({ flipper_id: @submission.user_uuid })
extras_redesign = Flipper.enabled?(:disability_compensation_0781v2_extras_redesign,
user) && form_id == FORM_ID_0781V2
fill_options = { extras_redesign: }
pdf_path = PdfFill::Filler.fill_ancillary_form(form_content, evss_claim_id, form_id, fill_options)
# If extras redesign is enabled, the stamp is added during the fill_ancillary_form call as part of the redesign.
return pdf_path if extras_redesign
stamped_path = PDFUtilities::DatestampPdf.new(pdf_path).run(text: 'VA.gov Submission', x: 510, y: 775,
text_only: true)
if form_id == FORM_ID_0781V2
PDFUtilities::DatestampPdf.new(stamped_path).run(
text: "Signed electronically and submitted via VA.gov at #{format_timestamp(submission_date)}. " \
'Signee signed with an identity-verified account.',
x: 5, y: 5, text_only: true, size: 9
)
else
PDFUtilities::DatestampPdf.new(stamped_path).run(text: 'VA.gov', x: 5, y: 5, timestamp: submission_date)
end
end
# Formats the timestamp for the PDF footer
def format_timestamp(datetime)
return nil if datetime.blank?
utc_time = datetime.utc
"#{utc_time.strftime('%H:%M')} UTC #{utc_time.strftime('%Y-%m-%d')}"
end
def get_evss_claim_metadata(pdf_path, form_id)
pdf_path_split = pdf_path.split('/')
{
doc_type: FORMS_METADATA[form_id][:docType],
file_name: pdf_path_split.last
}
end
def create_document_data(evss_claim_id, upload_data)
EVSSClaimDocument.new(
evss_claim_id:,
file_name: upload_data[:file_name],
tracked_item_id: nil,
document_type: upload_data[:doc_type]
)
end
def upload_to_vbms(pdf_path, form_id)
upload_data = get_evss_claim_metadata(pdf_path, form_id)
document_data = create_document_data(evss_claim_id, upload_data)
raise Common::Exceptions::ValidationErrors, document_data unless document_data.valid?
# thin wrapper to isolate upload for logging
file_body = File.read(pdf_path)
perform_client_upload(file_body, document_data, form_id)
ensure
# Delete the temporary PDF file
File.delete(pdf_path) if pdf_path.present?
end
def perform_client_upload(file_body, document_data, form_id)
if Flipper.enabled?(:disability_compensation_use_api_provider_for_0781_uploads)
provider = self.class.api_upload_provider(submission, form_id)
upload_document = provider.generate_upload_document(document_data.file_name)
provider.submit_upload_document(upload_document, file_body)
else
EVSS::DocumentsService.new(submission.auth_headers).upload(file_body, document_data)
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/submit_uploads.rb
|
# frozen_string_literal: true
require 'logging/call_location'
require 'zero_silent_failures/monitor'
module EVSS
module DisabilityCompensationForm
class SubmitUploads < Job
STATSD_KEY_PREFIX = 'worker.evss.submit_form526_upload'
ZSF_DD_TAG_FUNCTION = '526_evidence_upload_failure_email_queuing'
# retry for 2d 1h 47m 12s
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
sidekiq_options retry: 16
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
form526_submission_id = msg['args'].first
upload_data = msg['args'][1]
# Match existing data check in perform method
upload_data = upload_data.first if upload_data.is_a?(Array)
log_info = { job_id:, error_class:, error_message:, timestamp:, form526_submission_id: }
Rails.logger.warn('Submit Form 526 Upload Retries exhausted', log_info)
form_job_status = Form526JobStatus.find_by(job_id:)
bgjob_errors = form_job_status.bgjob_errors || {}
new_error = {
"#{timestamp.to_i}": {
caller_method: __method__.to_s,
error_class:,
error_message:,
timestamp:,
form526_submission_id:
}
}
form_job_status.update(
status: Form526JobStatus::STATUS[:exhausted],
bgjob_errors: bgjob_errors.merge(new_error)
)
StatsD.increment("#{STATSD_KEY_PREFIX}.exhausted")
if Flipper.enabled?(:disability_compensation_use_api_provider_for_submit_veteran_upload)
submission = Form526Submission.find(form526_submission_id)
provider = api_upload_provider(submission, upload_data['attachmentId'], nil)
provider.log_uploading_job_failure(self, error_class, error_message)
end
if Flipper.enabled?(:form526_send_document_upload_failure_notification)
guid = upload_data['confirmationCode']
Form526DocumentUploadFailureEmail.perform_async(form526_submission_id, guid)
end
# NOTE: do NOT add any additional code here between the failure email being enqueued and the rescue block.
# The mailer prevents an upload from failing silently, since we notify the veteran and provide a workaround.
# The rescue will catch any errors in the sidekiq_retries_exhausted block and mark a "silent failure".
# This shouldn't happen if an email was sent; there should be no code here to throw an additional exception.
# The mailer should be the last thing that can fail.
rescue => e
cl = caller_locations.first
call_location = Logging::CallLocation.new(ZSF_DD_TAG_FUNCTION, cl.path, cl.lineno)
zsf_monitor = ZeroSilentFailures::Monitor.new(Form526Submission::ZSF_DD_TAG_SERVICE)
user_account_id = begin
Form526Submission.find(form526_submission_id).user_account_id
rescue
nil
end
zsf_monitor.log_silent_failure(log_info, user_account_id, call_location:)
::Rails.logger.error(
'Failure in SubmitUploads#sidekiq_retries_exhausted',
{
messaged_content: e.message,
job_id:,
submission_id: form526_submission_id,
pre_exhaustion_failure: {
error_class:,
error_message:
}
}
)
raise e
end
def self.api_upload_provider(submission, document_type, supporting_evidence_attachment)
user = User.find(submission.user_uuid)
ApiProviderFactory.call(
type: ApiProviderFactory::FACTORIES[:supplemental_document_upload],
options: {
form526_submission: submission,
document_type:,
statsd_metric_prefix: STATSD_KEY_PREFIX,
supporting_evidence_attachment:
},
current_user: user,
feature_toggle: ApiProviderFactory::FEATURE_TOGGLE_SUBMIT_VETERAN_UPLOADS
)
end
# Recursively submits a file in a new instance of this job for each upload in the uploads list
#
# @param submission_id [Integer] The {Form526Submission} id
# @param upload_data [String] Form metadata for attachment, including upload GUID in AWS S3
#
def perform(submission_id, upload_data)
Sentry.set_tags(source: '526EZ-all-claims')
super(submission_id)
upload_data = upload_data.first if upload_data.is_a?(Array) # temporary for transition
guid = upload_data&.dig('confirmationCode')
with_tracking("Form526 Upload: #{guid}", submission.saved_claim_id, submission.id) do
sea = SupportingEvidenceAttachment.find_by(guid:)
file_body = sea&.get_file&.read
raise ArgumentError, "supporting evidence attachment with guid #{guid} has no file data" if file_body.nil?
document_data = create_document_data(upload_data, sea.converted_filename)
raise Common::Exceptions::ValidationErrors, document_data unless document_data.valid?
if Flipper.enabled?(:disability_compensation_use_api_provider_for_submit_veteran_upload)
upload_via_api_provider(submission, upload_data, file_body, sea)
else
EVSS::DocumentsService.new(submission.auth_headers).upload(file_body, document_data)
end
end
rescue => e
# Can't send a job manually to the dead set.
# Log and re-raise so the job ends up in the dead set and the parent batch is not marked as complete.
retryable_error_handler(e)
end
private
# Will upload the document via a SupplementalDocumentUploadProvider
# We use these providers to iteratively migrate uploads to Lighthouse
#
# @param submission [Form526Submission]
# @param upload_data [Hash] the form metadata for the attachment
# @param file_body [string] Attachment file contents
# @param attachment [SupportingEvidenceAttachment] Upload attachment record
def upload_via_api_provider(submission, upload_data, file_body, attachment)
document_type = upload_data['attachmentId']
provider = self.class.api_upload_provider(submission, document_type, attachment)
# Fall back to name in metadata if converted_filename returns nil; matches existing behavior
filename = attachment.converted_filename || upload_data['name']
upload_document = provider.generate_upload_document(filename)
provider.submit_upload_document(upload_document, file_body)
end
def retryable_error_handler(error)
super(error)
raise error
end
def create_document_data(upload_data, converted_filename)
EVSSClaimDocument.new(
evss_claim_id: submission.submitted_claim_id,
file_name: converted_filename || upload_data['name'],
tracked_item_id: nil,
document_type: upload_data['attachmentId']
)
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/submit_form526_cleanup.rb
|
# frozen_string_literal: true
module EVSS
module DisabilityCompensationForm
class SubmitForm526Cleanup < Job
include Sidekiq::Job
STATSD_KEY_PREFIX = 'worker.evss.submit_form526_cleanup'
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
form526_submission_id = msg['args'].first
form_job_status = Form526JobStatus.find_by(job_id:)
bgjob_errors = form_job_status.bgjob_errors || {}
new_error = {
"#{timestamp.to_i}": {
caller_method: __method__.to_s,
error_class:,
error_message:,
timestamp:,
form526_submission_id:
}
}
form_job_status.update(
status: Form526JobStatus::STATUS[:exhausted],
bgjob_errors: bgjob_errors.merge(new_error)
)
StatsD.increment("#{STATSD_KEY_PREFIX}.exhausted")
::Rails.logger.warn(
'Submit Form 526 Cleanup Retries exhausted',
{ job_id:, error_class:, error_message:, timestamp:, form526_submission_id: }
)
rescue => e
::Rails.logger.error(
'Failure in SubmitForm526Cleanup#sidekiq_retries_exhausted',
{
messaged_content: e.message,
job_id:,
submission_id: form526_submission_id,
pre_exhaustion_failure: {
error_class:,
error_message:
}
}
)
raise e
end
# Cleans up a 526 submission by removing its {InProgressForm}
#
# @param submission_id [Integer] The {Form526Submission} id
#
def perform(submission_id)
Sentry.set_tags(source: '526EZ-all-claims')
super(submission_id)
with_tracking('Form526 Cleanup', submission.saved_claim_id, submission.id) do
InProgressForm.find_by(form_id: FormProfiles::VA526ez::FORM_ID, user_uuid: submission.user_uuid)&.destroy
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/form526_document_upload_failure_email.rb
|
# frozen_string_literal: true
require 'logging/call_location'
require 'va_notify/service'
require 'zero_silent_failures/monitor'
module EVSS
module DisabilityCompensationForm
class Form526DocumentUploadFailureEmail < Job
STATSD_METRIC_PREFIX = 'api.form_526.veteran_notifications.document_upload_failure_email'
ZSF_DD_TAG_FUNCTION = '526_evidence_upload_failure_email_queuing'
VA_NOTIFY_CALLBACK_OPTIONS = {
callback_metadata: {
notification_type: 'error',
form_number: Form526Submission::FORM_526,
statsd_tags: { service: Form526Submission::ZSF_DD_TAG_SERVICE, function: ZSF_DD_TAG_FUNCTION }
}
}.freeze
# retry for 2d 1h 47m 12s
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
sidekiq_options retry: 16
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
form526_submission_id, supporting_evidence_attachment_guid = msg['args']
log_info = { job_id:, timestamp:, form526_submission_id:, error_class:, error_message:,
supporting_evidence_attachment_guid: }
Rails.logger.warn('Form526DocumentUploadFailureEmail retries exhausted', log_info)
# Job status records are upserted in the JobTracker module
# when the retryable_error_handler is called
form_job_status = Form526JobStatus.find_by(job_id:)
bgjob_errors = form_job_status.bgjob_errors || {}
new_error = {
"#{timestamp.to_i}": {
caller_method: __method__.to_s,
timestamp:,
form526_submission_id:,
supporting_evidence_attachment_guid:
}
}
form_job_status.update(
status: Form526JobStatus::STATUS[:exhausted],
bgjob_errors: bgjob_errors.merge(new_error)
)
rescue => e
Rails.logger.error(
'Failure in Form526DocumentUploadFailureEmail#sidekiq_retries_exhausted',
{
job_id:,
messaged_content: e.message,
submission_id: form526_submission_id,
supporting_evidence_attachment_guid:,
pre_exhaustion_failure: {
error_class:,
error_message:
}
}
)
raise e
ensure
StatsD.increment("#{STATSD_METRIC_PREFIX}.exhausted")
cl = caller_locations.first
call_location = Logging::CallLocation.new(ZSF_DD_TAG_FUNCTION, cl.path, cl.lineno)
zsf_monitor = ZeroSilentFailures::Monitor.new(Form526Submission::ZSF_DD_TAG_SERVICE)
user_account_id = begin
Form526Submission.find(form526_submission_id).user_account_id
rescue
nil
end
zsf_monitor.log_silent_failure(log_info, user_account_id, call_location:)
end
def perform(form526_submission_id, supporting_evidence_attachment_guid)
super(form526_submission_id)
submission = Form526Submission.find(form526_submission_id)
with_tracking('Form526DocumentUploadFailureEmail', submission.saved_claim_id, form526_submission_id) do
send_notification_mailer(submission, supporting_evidence_attachment_guid)
end
rescue => e
retryable_error_handler(e)
end
private
def send_notification_mailer(submission, supporting_evidence_attachment_guid)
form_attachment = SupportingEvidenceAttachment.find_by!(guid: supporting_evidence_attachment_guid)
# We need to obscure the original filename as it may contain PII
obscured_filename = form_attachment.obscured_filename
email_address = submission.veteran_email_address
first_name = submission.get_first_name
date_submitted = submission.format_creation_time_for_mailers
notify_service_bd = Settings.vanotify.services.benefits_disability
notify_client = VaNotify::Service.new(notify_service_bd.api_key, VA_NOTIFY_CALLBACK_OPTIONS)
template_id = notify_service_bd.template_id.form526_document_upload_failure_notification_template_id
va_notify_response = notify_client.send_email(
email_address:,
template_id:,
personalisation: { first_name:, filename: obscured_filename, date_submitted: }
)
log_info = { obscured_filename:, form526_submission_id: submission.id,
supporting_evidence_attachment_guid:, timestamp: Time.now.utc, va_notify_response: }
log_mailer_dispatch(log_info)
end
def log_mailer_dispatch(log_info)
StatsD.increment("#{STATSD_METRIC_PREFIX}.success")
Rails.logger.info('Form526DocumentUploadFailureEmail notification dispatched', log_info)
end
def retryable_error_handler(error)
super(error)
raise error
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/form4142_document_upload_failure_email.rb
|
# frozen_string_literal: true
require 'logging/call_location'
require 'va_notify/service'
require 'zero_silent_failures/monitor'
module EVSS
module DisabilityCompensationForm
class Form4142DocumentUploadFailureEmail < Job
STATSD_METRIC_PREFIX = 'api.form_526.veteran_notifications.form4142_upload_failure_email'
ZSF_DD_TAG_FUNCTION = '526_form_4142_upload_failure_email_sending'
VA_NOTIFY_CALLBACK_OPTIONS = {
callback_metadata: {
notification_type: 'error',
form_number: Form526Submission::FORM_526,
statsd_tags: { service: Form526Submission::ZSF_DD_TAG_SERVICE, function: ZSF_DD_TAG_FUNCTION }
}
}.freeze
# retry for 2d 1h 47m 12s
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
sidekiq_options retry: 16
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
form526_submission_id = msg['args'].first
log_info = { job_id:, timestamp:, form526_submission_id:, error_class:, error_message: }
Rails.logger.warn(
'Form4142DocumentUploadFailureEmail retries exhausted',
log_info
)
# Job status records are upserted in the JobTracker module
# when the retryable_error_handler is called
form_job_status = Form526JobStatus.find_by(job_id:)
bgjob_errors = form_job_status.bgjob_errors || {}
new_error = {
"#{timestamp.to_i}": {
caller_method: __method__.to_s,
timestamp:,
form526_submission_id:
}
}
form_job_status.update(
status: Form526JobStatus::STATUS[:exhausted],
bgjob_errors: bgjob_errors.merge(new_error)
)
rescue => e
Rails.logger.error(
'Failure in Form4142DocumentUploadFailureEmail#sidekiq_retries_exhausted',
{
job_id:,
messaged_content: e.message,
submission_id: form526_submission_id,
pre_exhaustion_failure: {
error_class:,
error_message:
}
}
)
raise e
ensure
StatsD.increment("#{STATSD_METRIC_PREFIX}.exhausted")
cl = caller_locations.first
call_location = Logging::CallLocation.new(ZSF_DD_TAG_FUNCTION, cl.path, cl.lineno)
user_account_id = begin
Form526Submission.find(form526_submission_id).user_account_id
rescue
nil
end
ZeroSilentFailures::Monitor.new(Form526Submission::ZSF_DD_TAG_SERVICE).log_silent_failure(
log_info,
user_account_id,
call_location:
)
end
def perform(form526_submission_id)
form526_submission = Form526Submission.find(form526_submission_id)
with_tracking('Form4142DocumentUploadFailureEmail', form526_submission.saved_claim_id, form526_submission_id) do
notify_client = VaNotify::Service.new(Settings.vanotify.services.benefits_disability.api_key,
VA_NOTIFY_CALLBACK_OPTIONS)
email_address = form526_submission.veteran_email_address
first_name = form526_submission.get_first_name
date_submitted = form526_submission.format_creation_time_for_mailers
va_notify_response = notify_client.send_email(
email_address:,
template_id: mailer_template_id,
personalisation: {
first_name:,
date_submitted:
}
)
log_info = { form526_submission_id:, timestamp: Time.now.utc, va_notify_response: }
log_mailer_dispatch(log_info)
end
rescue => e
retryable_error_handler(e)
end
private
def zsf_monitor
@zsf_monitor ||= ZeroSilentFailures::Monitor.new(Form526Submission::ZSF_DD_TAG_SERVICE)
end
def retryable_error_handler(error)
# Needed to log the error properly in the Sidekiq::Form526JobStatusTracker::JobTracker,
# which is included near the top of this job's inheritance tree in EVSS::DisabilityCompensationForm::JobStatus
super(error)
raise error
end
def log_mailer_dispatch(log_info)
Rails.logger.info('Form4142DocumentUploadFailureEmail notification dispatched', log_info)
StatsD.increment("#{STATSD_METRIC_PREFIX}.success")
end
def mailer_template_id
Settings.vanotify.services
.benefits_disability.template_id.form4142_upload_failure_notification_template_id
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/upload_bdd_instructions.rb
|
# frozen_string_literal: true
require 'logging/third_party_transaction'
module EVSS
module DisabilityCompensationForm
class UploadBddInstructions < Job
extend Logging::ThirdPartyTransaction::MethodWrapper
STATSD_KEY_PREFIX = 'worker.evss.submit_form526_bdd_instructions'
# 'Other Correspondence' document type
BDD_INSTRUCTIONS_DOCUMENT_TYPE = 'L023'
BDD_INSTRUCTIONS_FILE_NAME = 'BDD_Instructions.pdf'
# retry for 2d 1h 47m 12s
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
sidekiq_options retry: 16
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
form526_submission_id = msg['args'].first
form_job_status = Form526JobStatus.find_by(job_id:)
bgjob_errors = form_job_status.bgjob_errors || {}
new_error = {
"#{timestamp.to_i}": {
caller_method: __method__.to_s,
error_class:,
error_message:,
timestamp:,
form526_submission_id:
}
}
form_job_status.update(
status: Form526JobStatus::STATUS[:exhausted],
bgjob_errors: bgjob_errors.merge(new_error)
)
if Flipper.enabled?(:disability_compensation_use_api_provider_for_bdd_instructions)
submission = Form526Submission.find(form526_submission_id)
provider = api_upload_provider(submission)
provider.log_uploading_job_failure(self, error_class, error_message)
end
StatsD.increment("#{STATSD_KEY_PREFIX}.exhausted")
::Rails.logger.warn(
'Submit Form 526 Upload BDD Instructions Retries exhausted',
{ job_id:, error_class:, error_message:, timestamp:, form526_submission_id: }
)
rescue => e
::Rails.logger.error(
'Failure in UploadBddInstructions#sidekiq_retries_exhausted',
{
messaged_content: e.message,
job_id:,
submission_id: form526_submission_id,
pre_exhaustion_failure: {
error_class:,
error_message:
}
}
)
raise e
end
wrap_with_logging(
:upload_bdd_instructions,
additional_class_logs: {
action: 'Upload BDD Instructions to EVSS'
},
additional_instance_logs: {
submission_id: %i[submission_id]
}
)
def self.api_upload_provider(submission)
user = User.find(submission.user_uuid)
ApiProviderFactory.call(
type: ApiProviderFactory::FACTORIES[:supplemental_document_upload],
options: {
form526_submission: submission,
document_type: BDD_INSTRUCTIONS_DOCUMENT_TYPE,
statsd_metric_prefix: STATSD_KEY_PREFIX
},
current_user: user,
feature_toggle: ApiProviderFactory::FEATURE_TOGGLE_UPLOAD_BDD_INSTRUCTIONS
)
end
# Submits a BDD instruction PDF in to EVSS
#
# @param submission_id [Integer] The {Form526Submission} id
#
def perform(submission_id)
@submission_id = submission_id
Sentry.set_tags(source: '526EZ-all-claims')
super(submission_id)
with_tracking('Form526 Upload BDD instructions:', submission.saved_claim_id, submission.id) do
upload_bdd_instructions
end
rescue => e
# Can't send a job manually to the dead set.
# Log and re-raise so the job ends up in the dead set and the parent batch is not marked as complete.
retryable_error_handler(e)
end
private
def upload_bdd_instructions
if Flipper.enabled?(:disability_compensation_use_api_provider_for_bdd_instructions)
provider = self.class.api_upload_provider(submission)
upload_document = provider.generate_upload_document(BDD_INSTRUCTIONS_FILE_NAME)
provider.submit_upload_document(upload_document, file_body)
else
EVSS::DocumentsService.new(submission.auth_headers).upload(file_body, document_data)
end
end
def file_body
@file_body ||= File.read('lib/evss/disability_compensation_form/bdd_instructions.pdf')
end
def retryable_error_handler(error)
super(error)
raise error
end
def document_data
@document_data ||= EVSSClaimDocument.new(
evss_claim_id: submission.submitted_claim_id,
file_name: BDD_INSTRUCTIONS_FILE_NAME,
tracked_item_id: nil,
document_type: BDD_INSTRUCTIONS_DOCUMENT_TYPE
)
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/form0781_document_upload_failure_email.rb
|
# frozen_string_literal: true
require 'logging/call_location'
require 'va_notify/service'
require 'zero_silent_failures/monitor'
module EVSS
module DisabilityCompensationForm
class Form0781DocumentUploadFailureEmail < Job
STATSD_METRIC_PREFIX = 'api.form_526.veteran_notifications.form0781_upload_failure_email'
ZSF_DD_TAG_FUNCTION = '526_form_0781_failure_email_queuing'
VA_NOTIFY_CALLBACK_OPTIONS = {
callback_metadata: {
notification_type: 'error',
form_number: Form526Submission::FORM_526,
statsd_tags: { service: Form526Submission::ZSF_DD_TAG_SERVICE, function: ZSF_DD_TAG_FUNCTION }
}
}.freeze
# retry for 2d 1h 47m 12s
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
sidekiq_options retry: 16
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
form526_submission_id = msg['args'].first
log_info = { job_id:, timestamp:, form526_submission_id:, error_class:, error_message: }
Rails.logger.warn('Form0781DocumentUploadFailureEmail retries exhausted', log_info)
# Job status records are upserted in the JobTracker module
# when the retryable_error_handler is called
form_job_status = Form526JobStatus.find_by(job_id:)
bgjob_errors = form_job_status.bgjob_errors || {}
new_error = {
"#{timestamp.to_i}": {
caller_method: __method__.to_s,
timestamp:,
form526_submission_id:
}
}
form_job_status.update(
status: Form526JobStatus::STATUS[:exhausted],
bgjob_errors: bgjob_errors.merge(new_error)
)
rescue => e
Rails.logger.error(
'Failure in Form0781DocumentUploadFailureEmail#sidekiq_retries_exhausted',
{
job_id:,
messaged_content: e.message,
submission_id: form526_submission_id,
pre_exhaustion_failure: {
error_class:,
error_message:
}
}
)
raise e
ensure
StatsD.increment("#{STATSD_METRIC_PREFIX}.exhausted")
cl = caller_locations.first
call_location = Logging::CallLocation.new(ZSF_DD_TAG_FUNCTION, cl.path, cl.lineno)
zsf_monitor = ZeroSilentFailures::Monitor.new(Form526Submission::ZSF_DD_TAG_SERVICE)
user_account_id = begin
Form526Submission.find(form526_submission_id).user_account_id
rescue
nil
end
zsf_monitor.log_silent_failure(log_info, user_account_id, call_location:)
end
def perform(form526_submission_id)
submission = Form526Submission.find(form526_submission_id)
with_tracking('Form0781DocumentUploadFailureEmail', submission.saved_claim_id, form526_submission_id) do
send_notification_mailer(submission)
end
rescue => e
retryable_error_handler(e)
end
private
def retryable_error_handler(error)
# Needed to log the error properly in the Sidekiq::Form526JobStatusTracker::JobTracker,
# which is included near the top of this job's inheritance tree in EVSS::DisabilityCompensationForm::JobStatus
super(error)
raise error
end
def send_notification_mailer(submission)
email_address = submission.veteran_email_address
first_name = submission.get_first_name
date_submitted = submission.format_creation_time_for_mailers
notify_service_bd = Settings.vanotify.services.benefits_disability
notify_client = VaNotify::Service.new(notify_service_bd.api_key, VA_NOTIFY_CALLBACK_OPTIONS)
template_id = notify_service_bd.template_id.form0781_upload_failure_notification_template_id
va_notify_response = notify_client.send_email(
email_address:,
template_id:,
personalisation: { first_name:, date_submitted: }
)
log_info = { form526_submission_id: submission.id, timestamp: Time.now.utc, va_notify_response: }
log_mailer_dispatch(log_info)
end
def log_mailer_dispatch(log_info)
StatsD.increment("#{STATSD_METRIC_PREFIX}.success")
Rails.logger.info('Form0781DocumentUploadFailureEmail notification dispatched', log_info)
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/form8940_document.rb
|
# frozen_string_literal: true
module EVSS
module DisabilityCompensationForm
# Document generator for the 8940 form
#
# @return [EVSSClaimDocument] An EVSS claim document ready for submission
#
class Form8940Document < EVSSDocument
FORM_ID = '21-8940' # form id for PTSD IU
DOC_TYPE = 'L149'
def initialize(submission)
form_content = parse_8940(submission.form[Form526Submission::FORM_8940])
@pdf_path = generate_stamp_pdf(form_content, submission.submitted_claim_id, FORM_ID) if form_content.present?
upload_data = get_evss_claim_metadata(@pdf_path, DOC_TYPE)
@document_data = create_document_data(submission.submitted_claim_id, upload_data, DOC_TYPE)
end
private
def parse_8940(parsed_form)
return '' if parsed_form['unemployability'].empty?
parsed_form.deep_dup
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/evss_document.rb
|
# frozen_string_literal: true
require 'pdf_utilities/datestamp_pdf'
require 'pdf_fill/filler'
module EVSS
module DisabilityCompensationForm
# Base document class for the 526 ancillary forms
#
# @!attribute pdf_path [String] The file path of the PDF
#
class EVSSDocument
# @return [String] the contents of the file
#
def file_body
File.read(@pdf_path)
end
# @return [EVSSClaimDocument] A new claim document instance
#
def data
@document_data
end
attr_reader :pdf_path
private
# Invokes Filler ancillary form method to generate PDF document
# Then calls method PDFUtilities::DatestampPdf to stamp the document.
# Its called twice, once to stamp with text "VA.gov YYYY-MM-DD" at the bottom of each page
# and second time to stamp with text "VA.gov Submission" at the top of each page
def generate_stamp_pdf(form_content, submitted_claim_id, form_id)
pdf_path = PdfFill::Filler.fill_ancillary_form(form_content, submitted_claim_id, form_id)
stamped_path1 = PDFUtilities::DatestampPdf.new(pdf_path).run(text: 'VA.gov', x: 5, y: 5)
PDFUtilities::DatestampPdf.new(stamped_path1).run(
text: 'VA.gov Submission',
x: 510,
y: 775,
text_only: true
)
end
def get_evss_claim_metadata(pdf_path, doc_type)
pdf_path_split = pdf_path.split('/')
{
doc_type:,
file_name: pdf_path_split.last
}
end
def create_document_data(evss_claim_id, upload_data, doc_type)
EVSSClaimDocument.new(
evss_claim_id:,
file_name: upload_data[:file_name],
tracked_item_id: nil,
document_type: doc_type
)
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/job.rb
|
# frozen_string_literal: true
module EVSS
module DisabilityCompensationForm
# Base class for jobs involved in the 526 submission workflow.
# Mixes in the JobStatus module so all sub-classes have automatic metrics and logging.
#
class Job
include Sidekiq::Job
include JobStatus
# Sub-classes should call super so that @submission id is available as an instance variable
#
# @param submission_id [Integer] The {Form526Submission} id
#
def perform(submission_id)
@submission_id = submission_id
end
private
def submission
@submission ||= Form526Submission.find(@submission_id)
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/submit_form526_all_claim.rb
|
# frozen_string_literal: true
require 'evss/disability_compensation_form/service'
module EVSS
module DisabilityCompensationForm
class SubmitForm526AllClaim < EVSS::DisabilityCompensationForm::SubmitForm526
# :nocov:
def service(auth_headers)
EVSS::DisabilityCompensationForm::Service.new(
auth_headers
)
end
# :nocov:
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/submit_form526.rb
|
# frozen_string_literal: true
require 'evss/disability_compensation_form/service_exception'
require 'evss/disability_compensation_form/gateway_timeout'
require 'evss/disability_compensation_form/form526_to_lighthouse_transform'
require 'logging/third_party_transaction'
require 'sidekiq/form526_job_status_tracker/job_tracker'
module EVSS
module DisabilityCompensationForm
class SubmitForm526 < Job
extend Logging::ThirdPartyTransaction::MethodWrapper
attr_accessor :submission_id
# Sidekiq has built in exponential back-off functionality for retries
# retry for 2d 1h 47m 12s
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
RETRY = 16
STATSD_KEY_PREFIX = 'worker.evss.submit_form526'
wrap_with_logging(
:submit_complete_form,
additional_class_logs: {
action: 'Begin overall 526 submission'
},
additional_instance_logs: {
submission_id: %i[submission_id]
}
)
sidekiq_options retry: RETRY, queue: 'low'
# This callback cannot be tested due to the limitations of `Sidekiq::Testing.fake!`
# :nocov:
sidekiq_retries_exhausted do |msg, _ex|
submission = nil
next_birls_jid = nil
# log, mark Form526JobStatus for submission as "exhausted"
begin
job_exhausted(msg, STATSD_KEY_PREFIX)
rescue => e
log_error(msg, e)
end
# Submit under different birls if avail
begin
submission = Form526Submission.find msg['args'].first
next_birls_jid = submission.submit_with_birls_id_that_hasnt_been_tried_yet!(
silence_errors_and_log: true,
extra_content_for_logs: { job_class: msg['class'].demodulize, job_id: msg['jid'] }
)
rescue => e
log_error(msg, e)
end
# if no more unused birls to attempt submit with, give up, let vet know
begin
notify_enabled = Flipper.enabled?(:disability_compensation_pif_fail_notification)
if submission && next_birls_jid.nil? && msg['error_message'] == 'PIF in use' && notify_enabled
first_name = submission.get_first_name&.capitalize || 'Sir or Madam'
params = submission.personalization_parameters(first_name)
Form526SubmissionFailedEmailJob.perform_async(params)
end
rescue => e
log_error(msg, e)
end
end
# :nocov:
# Class method to log errors that occur in the sidekiq_retries_exhausted callback
#
# @param msg [Hash] The Sidekiq message containing job metadata
# @param error [Exception] The error that occurred
#
def self.log_error(msg, error)
log_error_info = {}
log_error_info[:job_class] = msg['class'].demodulize
log_error_info[:job_id] = msg['jid']
log_error_info[:submission_id] = msg['args'].first
log_error_info[:error_message] = error.message
log_error_info[:original_job_failure_reason] = msg['error_message']
ensure
Rails.logger.error('SubmitForm526#sidekiq_retries_exhausted error', log_error_info)
end
# Performs an asynchronous job for submitting a form526 to an upstream
# submission service (currently EVSS)
#
# @param submission_id [Integer] The {Form526Submission} id
def perform(submission_id)
super(submission_id)
return if fail_submission_feature_enabled?(submission)
# This instantiates the service as defined by the inheriting object
# TODO: this meaningless variable assignment is required for the specs to pass, which
# indicates a problematic coupling of implementation and test logic. This should eventually
# be addressed to make this service and test more robust and readable.
service = service(submission.auth_headers)
with_tracking('Form526 Submission', submission.saved_claim_id, submission.id, submission.bdd?,
service_provider) do
submission.mark_birls_id_as_tried!
return unless successfully_prepare_submission_for_evss?(submission)
begin
response = choose_service_provider(submission, service)
response_handler(response)
send_post_evss_notifications(submission, true)
rescue => e
send_post_evss_notifications(submission, false)
handle_errors(submission, e)
end
end
end
private
# send submission data to either EVSS or Lighthouse (LH)
def choose_service_provider(submission, service)
if submission.claims_api? # not needed once fully migrated to LH
send_submission_data_to_lighthouse(submission, submission.account.icn)
else
service.submit_form526(submission.form_to_json(Form526Submission::FORM_526))
end
end
def service_provider
submission.claims_api? ? 'lighthouse' : 'evss'
end
def fail_submission_feature_enabled?(submission)
if Flipper.enabled?(:disability_compensation_fail_submission,
OpenStruct.new({ flipper_id: submission.user_uuid }))
with_tracking('Form526 Submission', submission.saved_claim_id, submission.id, submission.bdd?) do
Rails.logger.info("disability_compensation_fail_submission enabled for submission #{submission.id}")
throw StandardError
rescue => e
handle_errors(submission, e)
true
end
end
end
def successfully_prepare_submission_for_evss?(submission)
submission.prepare_for_evss!
true
rescue => e
handle_errors(submission, e)
false
end
def send_submission_data_to_lighthouse(submission, icn)
# 1. transform submission data to LH format
transform_service = EVSS::DisabilityCompensationForm::Form526ToLighthouseTransform.new
transaction_id = submission.system_transaction_id
body = transform_service.transform(submission.form['form526'])
# 2. send transformed submission data to LH endpoint
benefits_claims_service = BenefitsClaims::Service.new(icn)
raw_response = benefits_claims_service.submit526(body, nil, nil, { transaction_id: })
raw_response_body = if raw_response.body.is_a? String
JSON.parse(raw_response.body)
else
raw_response.body
end
# 3. convert LH raw response to a FormSubmitResponse for further processing (claim_id, status)
# parse claimId from LH response
submitted_claim_id = raw_response_body.dig('data', 'attributes', 'claimId').to_i
raw_response_struct = OpenStruct.new({
body: { claim_id: submitted_claim_id },
status: raw_response.status
})
EVSS::DisabilityCompensationForm::FormSubmitResponse.new(raw_response_struct.status, raw_response_struct)
end
def submit_complete_form
service.submit_form526(submission.form_to_json(Form526Submission::FORM_526))
end
def response_handler(response)
submission.submitted_claim_id = response.claim_id
submission.save
# send "Submitted" email with claim id here for primary path
submission.send_submitted_email("#{self.class}#response_handler primary path")
end
def send_post_evss_notifications(submission, send_notifications)
actor = OpenStruct.new({ flipper_id: submission.user_uuid })
if Flipper.enabled?(:disability_compensation_production_tester, actor)
Rails.logger.info("send_post_evss_notifications call skipped for submission #{submission.id}")
elsif send_notifications
submission.send_post_evss_notifications!
end
rescue => e
handle_errors(submission, e)
end
def handle_errors(submission, error)
error = retries_will_fail_error(error)
raise error
rescue Common::Exceptions::BackendServiceException,
Common::Exceptions::Unauthorized, # 401 (UnauthorizedError?)
# 422 (UpstreamUnprocessableEntity, i.e. EVSS container validation)
Common::Exceptions::UpstreamUnprocessableEntity,
Common::Exceptions::Timeout, Net::ReadTimeout, Faraday::TimeoutError, # Any forms of timeout errors
Common::Exceptions::TooManyRequests, # 429
Common::Exceptions::ClientDisconnected, # 499
Common::Exceptions::ExternalServerInternalServerError, # 500
Common::Exceptions::NotImplemented, # 501
Common::Exceptions::BadGateway, # 502
Common::Exceptions::ServiceUnavailable, # 503 (ServiceUnavailableException)
Common::Exceptions::GatewayTimeout, # 504
Breakers::OutageException => e
retryable_error_handler(submission, e)
rescue EVSS::DisabilityCompensationForm::ServiceException => e
# retry submitting the form for specific upstream errors
retry_form526_error_handler!(submission, e)
rescue => e
non_retryable_error_handler(submission, e)
end
# check if this error from the provider will fail retires
def retries_will_fail_error(error)
if error.instance_of?(Common::Exceptions::UnprocessableEntity)
error_clone = error.deep_dup
upstream_error = error_clone.errors.first.stringify_keys
unless (upstream_error['source'].present? && upstream_error['source']['pointer'].present?) ||
upstream_error['detail'].downcase.include?('retries will fail')
error = Common::Exceptions::UpstreamUnprocessableEntity.new(errors: error.errors)
end
end
error
end
def retryable_error_handler(_submission, error)
# update JobStatus, log and metrics in JobStatus#retryable_error_handler
super(error)
raise error
end
def non_retryable_error_handler(submission, error)
# update JobStatus, log and metrics in JobStatus#non_retryable_error_handler
super(error)
unless Flipper.enabled?(:disability_compensation_production_tester,
OpenStruct.new({ flipper_id: submission.user_uuid })) ||
Flipper.enabled?(:disability_compensation_fail_submission,
OpenStruct.new({ flipper_id: submission.user_uuid }))
submission.submit_with_birls_id_that_hasnt_been_tried_yet!(
silence_errors_and_log: true,
extra_content_for_logs: { job_class: self.class.to_s.demodulize, job_id: jid }
)
end
end
def send_rrd_alert(submission, error, subtitle)
message = "RRD could not submit the claim to EVSS: #{subtitle}<br/>"
submission.send_rrd_alert_email("RRD submission to EVSS error: #{subtitle}", message, error)
end
def service(_auth_headers)
raise NotImplementedError, 'Subclass of SubmitForm526 must implement #service'
end
# Logic for retrying a job due to an upstream service error.
# Retry if any upstream external service unavailability exceptions (unless it is caused by an invalid EP code)
# and any PIF-in-use exceptions are encountered.
# Otherwise the job is marked as non-retryable and completed.
#
# @param error [EVSS::DisabilityCompensationForm::ServiceException]
#
def retry_form526_error_handler!(submission, error)
if error.retryable?
retryable_error_handler(submission, error)
else
non_retryable_error_handler(submission, error)
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/submit_form8940.rb
|
# frozen_string_literal: true
require 'logging/third_party_transaction'
module EVSS
module DisabilityCompensationForm
class SubmitForm8940 < Job
extend Logging::ThirdPartyTransaction::MethodWrapper
STATSD_KEY_PREFIX = 'worker.evss.submit_form8940'
# Sidekiq has built in exponential back-off functionality for retries
# A max retry attempt of 16 will result in a run time of ~48 hours
# This job is invoked from 526 background job
RETRY = 16
sidekiq_options retry: RETRY
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
form526_submission_id = msg['args'].first
form_job_status = Form526JobStatus.find_by(job_id:)
bgjob_errors = form_job_status.bgjob_errors || {}
new_error = {
"#{timestamp.to_i}": {
caller_method: __method__.to_s,
error_class:,
error_message:,
timestamp:,
form526_submission_id:
}
}
form_job_status.update(
status: Form526JobStatus::STATUS[:exhausted],
bgjob_errors: bgjob_errors.merge(new_error)
)
StatsD.increment("#{STATSD_KEY_PREFIX}.exhausted")
::Rails.logger.warn(
'Submit Form 8940 Retries exhausted',
{ job_id:, error_class:, error_message:, timestamp:, form526_submission_id: }
)
rescue => e
::Rails.logger.error(
'Failure in SubmitForm8940#sidekiq_retries_exhausted',
{
messaged_content: e.message,
job_id:,
submission_id: form526_submission_id,
pre_exhaustion_failure: {
error_class:,
error_message:
}
}
)
raise e
end
attr_accessor :submission_id
wrap_with_logging(
:upload_to_vbms,
additional_class_logs: {
action: 'upload form 8940 to EVSS'
},
additional_instance_logs: {
submission_id: %i[submission_id]
}
)
def get_docs(submission_id)
@submission_id = submission_id
{ type: '21-8940', file: EVSS::DisabilityCompensationForm::Form8940Document.new(submission) }
end
# Performs an asynchronous job for generating and submitting 8940 PDF documents to VBMS
#
# @param submission_id [Integer] The {Form526Submission} id
#
def perform(submission_id)
@submission_id = submission_id
Sentry.set_tags(source: '526EZ-all-claims')
super(submission_id)
with_tracking('Form8940 Submission', submission.saved_claim_id, submission_id) do
upload_to_vbms
end
rescue => e
# Cannot move job straight to dead queue dynamically within an executing job
# raising error for all the exceptions as sidekiq will then move into dead queue
# after all retries are exhausted
retryable_error_handler(e)
raise e
end
private
def document
@document ||= EVSS::DisabilityCompensationForm::Form8940Document.new(submission)
end
def upload_to_vbms
client.upload(document.file_body, document.data)
ensure
# Delete the temporary PDF file
File.delete(document.pdf_path) if document.pdf_path.present?
end
def client
@client ||= if Flipper.enabled?(:disability_compensation_lighthouse_document_service_provider)
# TODO: create client from lighthouse document service
else
EVSS::DocumentsService.new(submission.auth_headers)
end
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/job_status.rb
|
# frozen_string_literal: true
require 'sidekiq/form526_job_status_tracker/job_tracker'
require 'sidekiq/form526_job_status_tracker/metrics'
module EVSS
module DisabilityCompensationForm
module JobStatus
extend ActiveSupport::Concern
include Sidekiq::Form526JobStatusTracker::JobTracker
# Module that is mixed in to {EVSS::DisabilityCompensationForm::Job} so that it's sub-classes
# get automatic metrics and logging.
#
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/evss
|
code_files/vets-api-private/app/sidekiq/evss/disability_compensation_form/metrics.rb
|
# frozen_string_literal: true
require 'sidekiq/form526_job_status_tracker/job_tracker'
module EVSS
module DisabilityCompensationForm
# Helper class that fires off StatsD metrics
#
# @param prefix [String] Will prefix all metric names
#
class Metrics
include Sidekiq::Form526JobStatusTracker::JobTracker
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/test_user_dashboard/daily_maintenance.rb
|
# frozen_string_literal: true
module TestUserDashboard
class DailyMaintenance
include Sidekiq::Job
TUD_ACCOUNTS_TABLE = 'tud_accounts'
def perform
checkin_tud_accounts
end
private
def checkin_tud_accounts
TestUserDashboard::TudAccount.where.not(checkout_time: nil).find_each do |account|
account.update(checkout_time: nil)
TestUserDashboard::AccountMetrics
.new(account)
.checkin(is_manual_checkin: true)
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/mhv/phr_update_job.rb
|
# frozen_string_literal: true
require 'medical_records/phr_mgr/client'
##
# For current MHV users, call the "PHR Refresh" API in MHV to update their medical records in the
# FHIR server.
#
module MHV
class PhrUpdateJob
include Sidekiq::Job
sidekiq_options retry: false
def perform(icn, mhv_correlation_id)
run_refresh(icn) if mhv_user?(mhv_correlation_id)
rescue => e
handle_errors(e)
end
private
def run_refresh(icn)
phr_client = PHRMgr::Client.new(icn)
phr_client.post_phrmgr_refresh
end
def mhv_user?(mhv_correlation_id)
mhv_correlation_id.present?
end
def handle_errors(e)
Rails.logger.error("MHV PHR refresh failed: #{e.message}", e)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/mhv/account_creator_job.rb
|
# frozen_string_literal: true
require 'mhv/user_account/creator'
module MHV
class AccountCreatorJob
include Sidekiq::Job
sidekiq_options retry: false, unique_for: 5.minutes
def perform(user_verification_id)
user_verification = UserVerification.find(user_verification_id)
MHV::UserAccount::Creator.new(user_verification:, break_cache: true).perform
rescue ActiveRecord::RecordNotFound
Rails.logger.error("MHV AccountCreatorJob failed: UserVerification not found for id #{user_verification_id}")
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/form1095/delete_old1095_bs_job.rb
|
# frozen_string_literal: true
module Form1095
class DeleteOld1095BsJob
include Sidekiq::Job
# This job deletes Form1095B forms for years prior to the current tax year.
# Limiting the number of records deleted in a single batch to prevent database impact.
# This limit can be overriden when running manually.
def perform(limit = 100_000)
forms_to_delete = Form1095B.where('tax_year < ?', Form1095B.current_tax_year).limit(limit)
if forms_to_delete.none?
log_message('No old Form1095B records to delete')
return
end
log_message("Begin deleting #{forms_to_delete.count} old Form1095B files")
start_time = Time.now.to_f
forms_to_delete.in_batches(&:delete_all)
duration = Time.now.to_f - start_time
log_message("Finished deleting old Form1095B files in #{duration} seconds")
end
private
def log_message(message)
Rails.logger.info("Form1095B Deletion Job: #{message}")
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/form1095/new1095_bs_job.rb
|
# frozen_string_literal: true
module Form1095
class New1095BsJob
include Sidekiq::Job
sidekiq_options(retry: false)
def perform
log_message(:info, 'Checking for new 1095-B data')
file_names = get_bucket_files
if file_names.empty?
log_message(:info, 'No new 1095 files found')
else
log_message(:info, "#{file_names.size} files found")
end
files_read_count = 0
file_names.each do |file_name|
if download_and_process_file?(file_name)
files_read_count += 1
log_message(:info, "Successfully read #{@form_count} 1095B forms from #{file_name}, deleting file from S3")
bucket.delete_objects(delete: { objects: [{ key: file_name }] })
else
message = "failed to save #{@error_count} forms from file: #{file_name}; " \
"successfully saved #{@form_count} forms"
log_message(:error, message)
end
end
log_message(:info, "#{files_read_count}/#{file_names.size} files read successfully")
end
private
# used to enable datadog monitoring
def log_message(level, message)
Rails.logger.send(level, "Form1095B Creation Job #{level.capitalize}: #{message}")
end
def bucket
@bucket ||= Aws::S3::Resource.new(
region: Settings.form1095_b.s3.region,
access_key_id: Settings.form1095_b.s3.aws_access_key_id,
secret_access_key: Settings.form1095_b.s3.aws_secret_access_key
).bucket(Settings.form1095_b.s3.bucket)
end
def get_bucket_files
# grabs available file names from bucket
bucket.objects({ prefix: 'MEC', delimiter: '/' }).collect(&:key)
end
def parse_file_name(file_name)
return {} if file_name.blank?
file_values = file_name.sub('.txt', '').split('_')
year = file_values[3].to_i
ts = file_values[-1]
{
is_dep_file?: file_values.include?('B'),
isOg?: file_values.include?('O'),
tax_year: year,
timestamp: ts,
name: file_name
}
end
def gen_address(addr1, addr2, addr3)
addr1.concat(' ', addr2 || '', ' ', addr3 || '').strip
end
def get_form_fields(data)
fields = {}
data.each_with_index do |field, ndx|
next if ndx < 3
vals = field.split('=')
value = nil
value = vals[1] if vals[1] && vals[1].downcase != 'null'
fields[vals[0].to_sym] = value
end
fields
end
def get_coverage_array(form_fields)
coverage_arr = []
i = 1
while i <= 13
val = "H#{i < 10 ? '0' : ''}#{i}"
field = form_fields[val.to_sym]
coverage_arr.push((field && field.strip == 'Y') || false)
i += 1
end
coverage_arr
end
def produce_1095_hash(form_fields, unique_id, coverage_arr)
{
unique_id:,
veteran_icn: form_fields[:A15]&.gsub(/\A0{6}|0{6}\z/, ''),
form_data: {
last_name: form_fields[:A01] || '',
first_name: form_fields[:A02] || '',
middle_name: form_fields[:A03] || '',
last_4_ssn: form_fields[:A16] ? form_fields[:A16][-4...] : '',
birth_date: form_fields[:N03] || '',
address: gen_address(form_fields[:B01] || ''.dup, form_fields[:B02], form_fields[:B03]),
city: form_fields[:B04] || '',
state: form_fields[:B05] || '',
country: form_fields[:B06] || '',
zip_code: form_fields[:B07] || '',
foreign_zip: form_fields[:B08] || '',
province: form_fields[:B10] || '',
coverage_months: coverage_arr
}
}
end
def parse_form(form)
data = form.split('^')
unique_id = data[2]
form_fields = get_form_fields(data)
coverage_arr = get_coverage_array(form_fields)
produce_1095_hash(form_fields, unique_id, coverage_arr)
end
def save_data?(form_data, corrected)
existing_form = Form1095B.find_by(veteran_icn: form_data[:veteran_icn], tax_year: form_data[:tax_year])
if !corrected && existing_form.present? # returns true to indicate successful entry
return true
elsif corrected && existing_form.nil?
log_message(:warn, "Form for year #{form_data[:tax_year]} not found, but file is for Corrected 1095-B forms.")
end
rv = false
if existing_form.nil?
form = Form1095B.new(form_data)
rv = form.save
else
rv = existing_form.update(form_data)
end
@form_count += 1 if rv
rv
end
def process_line?(form, file_details)
data = parse_form(form)
# we can't save records without icns and should not retain the file in cases
# where the icn is missing
return true if data[:veteran_icn].blank?
corrected = !file_details[:isOg?]
data[:tax_year] = file_details[:tax_year]
data[:form_data][:is_corrected] = corrected
data[:form_data][:is_beneficiary] = file_details[:is_dep_file?]
data[:form_data] = data[:form_data].to_json
unique_id = data[:unique_id]
data.delete(:unique_id)
unless save_data?(data, corrected)
@error_count += 1
log_message(:warn, "Failed to save form with unique ID: #{unique_id}")
return false
end
true
end
def process_file?(temp_file, file_details)
all_succeeded = true
lines = 0
temp_file.each_line do |form|
lines += 1
successful_line = process_line?(form, file_details)
all_succeeded = false if !successful_line && all_succeeded
end
temp_file.close
temp_file.unlink
all_succeeded
rescue => e
message = "Error processing file: #{file_details[:name]}, on line #{lines}; #{e.message}"
log_message(:error, message)
false
end
# downloading file to the disk and then reading that file,
# this will allow us to read large S3 files without exhausting resources/crashing the system
def download_and_process_file?(file_name)
log_message(:info, "processing file: #{file_name}")
@form_count = 0
@error_count = 0
file_details = parse_file_name(file_name)
return false if file_details.blank?
return true if file_details[:tax_year] < Form1095B.current_tax_year
# downloads S3 file into local file, allows for processing large files this way
temp_file = Tempfile.new(file_name, encoding: 'ascii-8bit')
# downloads file into temp_file
bucket.object(file_name).get(response_target: temp_file)
process_file?(temp_file, file_details)
rescue => e
log_message(:error, e.message)
false
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/event_bus_gateway/letter_ready_email_job.rb
|
# frozen_string_literal: true
require 'sidekiq'
require 'sidekiq/attr_package'
require_relative 'constants'
require_relative 'letter_ready_job_concern'
module EventBusGateway
class LetterReadyEmailJob
include Sidekiq::Job
include LetterReadyJobConcern
STATSD_METRIC_PREFIX = 'event_bus_gateway.letter_ready_email'
sidekiq_options retry: Constants::SIDEKIQ_RETRY_COUNT_FIRST_EMAIL
sidekiq_retry_in do |count, _exception|
# Sidekiq default exponential backoff with jitter, plus one hour
(count**4) + 15 + (rand(10) * (count + 1)) + 1.hour.to_i
end
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
::Rails.logger.error('LetterReadyEmailJob retries exhausted',
{ job_id:, timestamp:, error_class:, error_message: })
tags = Constants::DD_TAGS + ["function: #{error_message}"]
StatsD.increment("#{STATSD_METRIC_PREFIX}.exhausted", tags:)
end
def perform(participant_id, template_id, cache_key = nil)
first_name = nil
icn = nil
# Retrieve PII from Redis if cache_key provided (avoids PII exposure in logs)
if cache_key
attributes = Sidekiq::AttrPackage.find(cache_key)
if attributes
first_name = attributes[:first_name]
icn = attributes[:icn]
end
end
# Fallback to fetching if cache_key not provided or failed
first_name ||= get_first_name_from_participant_id(participant_id)
icn ||= get_icn(participant_id)
return unless validate_email_prerequisites(template_id, first_name, icn)
send_email_notification(participant_id, template_id, first_name, icn)
StatsD.increment("#{STATSD_METRIC_PREFIX}.success", tags: Constants::DD_TAGS)
# Clean up PII from Redis if cache_key was used
Sidekiq::AttrPackage.delete(cache_key) if cache_key
rescue => e
record_notification_send_failure(e, 'Email')
raise
end
private
def validate_email_prerequisites(template_id, first_name, icn)
if icn.blank?
log_email_skipped('ICN not available', template_id)
return false
end
if first_name.blank?
log_email_skipped('First Name not available', template_id)
return false
end
true
end
def log_email_skipped(reason, template_id)
::Rails.logger.error(
'LetterReadyEmailJob email skipped',
{
notification_type: 'email',
reason:,
template_id:
}
)
tags = Constants::DD_TAGS + ['notification_type:email', "reason:#{reason.parameterize.underscore}"]
StatsD.increment("#{STATSD_METRIC_PREFIX}.skipped", tags:)
end
def send_email_notification(participant_id, template_id, first_name, icn)
response = notify_client.send_email(
recipient_identifier: { id_value: participant_id, id_type: 'PID' },
template_id:,
personalisation: {
host: hostname_for_template,
first_name: first_name&.capitalize
}
)
create_notification_record(template_id, icn, response&.id)
end
def create_notification_record(template_id, icn, va_notify_id)
notification = EventBusGatewayNotification.create(
user_account: user_account(icn),
template_id:,
va_notify_id:
)
return if notification.persisted?
::Rails.logger.warn(
'LetterReadyEmailJob notification record failed to save',
{
errors: notification.errors.full_messages,
template_id:,
va_notify_id:
}
)
end
def hostname_for_template
Constants::HOSTNAME_MAPPING[Settings.hostname] || Settings.hostname
end
def notify_client
@notify_client ||= VaNotify::Service.new(
Constants::NOTIFY_SETTINGS.api_key,
{ callback_klass: 'EventBusGateway::VANotifyEmailStatusCallback' }
)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/event_bus_gateway/letter_ready_job_concern.rb
|
# frozen_string_literal: true
require_relative 'errors'
module EventBusGateway
module LetterReadyJobConcern
extend ActiveSupport::Concern
private
def get_bgs_person(participant_id)
@bgs_person ||= begin
bgs = BGS::Services.new(external_uid: participant_id, external_key: participant_id)
person = bgs.people.find_person_by_ptcpnt_id(participant_id)
raise Errors::BgsPersonNotFoundError, 'Participant ID cannot be found in BGS' if person.nil?
person
end
end
def get_mpi_profile(participant_id)
@mpi_profile ||= begin
person = get_bgs_person(participant_id)
mpi_response = MPI::Service.new.find_profile_by_attributes(
first_name: person[:first_nm]&.capitalize,
last_name: person[:last_nm]&.capitalize,
birth_date: person[:brthdy_dt]&.strftime('%Y%m%d'),
ssn: person[:ssn_nbr]
)
handle_mpi_response(mpi_response)
end
end
def handle_mpi_response(mpi_response)
raise Errors::MpiProfileNotFoundError, 'Failed to fetch MPI profile' if mpi_response.nil?
return mpi_response.profile if mpi_response.ok? && mpi_response.profile.present?
if mpi_response.server_error?
raise Common::Exceptions::BackendServiceException.new(
'MPI_502',
detail: 'MPI service returned a server error'
)
elsif mpi_response.not_found?
raise Errors::MpiProfileNotFoundError, 'MPI profile not found for participant'
else
# Unexpected state
raise Errors::MpiProfileNotFoundError, 'Failed to fetch MPI profile'
end
end
def get_first_name_from_participant_id(participant_id)
person = get_bgs_person(participant_id)
person&.dig(:first_nm)&.capitalize
end
def get_icn(participant_id)
get_mpi_profile(participant_id)&.icn
end
def record_notification_send_failure(error, job_type)
error_message = "LetterReady#{job_type}Job #{job_type.downcase} error"
::Rails.logger.error(error_message, { message: error.message })
tags = Constants::DD_TAGS + ["function: #{error_message}"]
StatsD.increment("#{self.class::STATSD_METRIC_PREFIX}.failure", tags:)
end
def user_account(icn)
UserAccount.find_by(icn:)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/event_bus_gateway/errors.rb
|
# frozen_string_literal: true
module EventBusGateway
module Errors
# Raised when MPI profile lookup fails
class MpiProfileNotFoundError < StandardError; end
# Raised when BGS person lookup fails
class BgsPersonNotFoundError < StandardError; end
# Raised when notification jobs fail to enqueue
class NotificationEnqueueError < StandardError; end
# Raised when ICN lookup fails or returns blank
class IcnNotFoundError < StandardError; end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/event_bus_gateway/letter_ready_push_job.rb
|
# frozen_string_literal: true
require 'sidekiq'
require 'sidekiq/attr_package'
require_relative 'constants'
require_relative 'errors'
require_relative 'letter_ready_job_concern'
module EventBusGateway
class LetterReadyPushJob
include Sidekiq::Job
include LetterReadyJobConcern
STATSD_METRIC_PREFIX = 'event_bus_gateway.letter_ready_push'
sidekiq_options retry: Constants::SIDEKIQ_RETRY_COUNT_FIRST_PUSH
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
::Rails.logger.error('LetterReadyPushJob retries exhausted',
{ job_id:, timestamp:, error_class:, error_message: })
tags = Constants::DD_TAGS + ["function: #{error_message}"]
StatsD.increment("#{STATSD_METRIC_PREFIX}.exhausted", tags:)
end
def perform(participant_id, template_id, cache_key = nil)
icn = nil
# Retrieve PII from Redis if cache_key provided (avoids PII exposure in logs)
if cache_key
attributes = Sidekiq::AttrPackage.find(cache_key)
icn = attributes[:icn] if attributes
end
# Fallback to fetching if cache_key not provided or failed
icn ||= get_icn(participant_id)
raise Errors::IcnNotFoundError, 'Failed to fetch ICN' if icn.blank?
send_push_notification(icn, template_id)
StatsD.increment("#{STATSD_METRIC_PREFIX}.success", tags: Constants::DD_TAGS)
# Clean up PII from Redis if cache_key was used
Sidekiq::AttrPackage.delete(cache_key) if cache_key
rescue => e
record_notification_send_failure(e, 'Push')
raise
end
private
def send_push_notification(icn, template_id)
notify_client.send_push(
mobile_app: 'VA_FLAGSHIP_APP',
recipient_identifier: { id_value: icn, id_type: 'ICN' },
template_id:,
personalisation: {}
)
create_push_notification_record(template_id, icn)
end
def create_push_notification_record(template_id, icn)
notification = EventBusGatewayPushNotification.create(
user_account: user_account(icn),
template_id:
)
return if notification.persisted?
::Rails.logger.warn(
'LetterReadyPushJob notification record failed to save',
{
errors: notification.errors.full_messages,
template_id:
}
)
end
def notify_client
# Push notifications require a separate API key from email and sms
@notify_client ||= VaNotify::Service.new(Constants::NOTIFY_SETTINGS.push_api_key)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/event_bus_gateway/va_notify_email_status_callback.rb
|
# frozen_string_literal: true
require_relative 'constants'
module EventBusGateway
class VANotifyEmailStatusCallback
class EventBusGatewayNotificationNotFoundError < StandardError; end
class MPIError < StandardError; end
class MPINameError < StandardError; end
STATSD_METRIC_PREFIX = 'event_bus_gateway.va_notify_email_status_callback'
def self.call(notification)
status = notification.status
add_metrics(status)
add_log(notification) if notification.status != 'delivered'
if notification.status == 'temporary-failure' && Flipper.enabled?(:event_bus_gateway_retry_emails)
retry_email(notification)
end
end
def self.retry_email(notification)
ebg_noti = find_notification_by_va_notify_id(notification.notification_id)
return handle_exhausted_retries(notification, ebg_noti) if ebg_noti.attempts >= Constants::MAX_EMAIL_ATTEMPTS
schedule_retry_job(ebg_noti)
StatsD.increment("#{STATSD_METRIC_PREFIX}.queued_retry_success", tags: Constants::DD_TAGS)
rescue => e
handle_retry_failure(e)
raise e
end
def self.find_notification_by_va_notify_id(va_notify_id)
ebg_noti = EventBusGatewayNotification.find_by(va_notify_id:)
raise EventBusGatewayNotificationNotFoundError if ebg_noti.nil?
ebg_noti
end
def self.handle_exhausted_retries(notification, ebg_noti)
add_exhausted_retry_log(notification, ebg_noti)
StatsD.increment("#{STATSD_METRIC_PREFIX}.exhausted_retries", tags: Constants::DD_TAGS)
end
def self.schedule_retry_job(ebg_noti)
icn = ebg_noti.user_account.icn
profile = get_profile_by_icn(icn)
personalisation = {
host: Constants::HOSTNAME_MAPPING[Settings.hostname] || Settings.hostname,
first_name: get_first_name(profile)
}
EventBusGateway::LetterReadyRetryEmailJob.perform_in(
1.hour,
profile.participant_id,
ebg_noti.template_id,
personalisation,
ebg_noti.id
)
end
def self.handle_retry_failure(error)
Rails.logger.error(name, error.message)
tags = Constants::DD_TAGS + ["function: #{error.message}"]
StatsD.increment("#{STATSD_METRIC_PREFIX}.queued_retry_failure", tags:)
end
def self.get_first_name(profile)
first_name = profile.given_names&.first
raise MPINameError unless first_name
first_name
end
def self.get_profile_by_icn(icn)
mpi_response = MPI::Service.new.find_profile_by_identifier(identifier: icn, identifier_type: MPI::Constants::ICN)
raise MPIError unless mpi_response.ok?
mpi_response.profile
end
def self.add_log(notification)
context = {
notification_id: notification.notification_id,
source_location: notification.source_location,
status: notification.status,
status_reason: notification.status_reason,
notification_type: notification.notification_type
}
Rails.logger.error(name, context)
end
def self.add_exhausted_retry_log(_notification, ebg_notification)
context = {
ebg_notification_id: ebg_notification.id,
max_attempts: Constants::MAX_EMAIL_ATTEMPTS
}
Rails.logger.error('EventBusGateway email retries exhausted', context)
end
def self.add_metrics(status)
case status
when 'delivered'
StatsD.increment('api.vanotify.notifications.delivered')
StatsD.increment('callbacks.event_bus_gateway.va_notify.notifications.delivered')
when 'permanent-failure'
StatsD.increment('api.vanotify.notifications.permanent_failure')
StatsD.increment('callbacks.event_bus_gateway.va_notify.notifications.permanent_failure')
when 'temporary-failure'
StatsD.increment('api.vanotify.notifications.temporary_failure')
StatsD.increment('callbacks.event_bus_gateway.va_notify.notifications.temporary_failure')
else
StatsD.increment('api.vanotify.notifications.other')
StatsD.increment('callbacks.event_bus_gateway.va_notify.notifications.other')
end
StatsD.increment("#{STATSD_METRIC_PREFIX}.va_notify.notifications.#{status}", tags: Constants::DD_TAGS)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/event_bus_gateway/constants.rb
|
# frozen_string_literal: true
module EventBusGateway
module Constants
# VA Notify service settings
NOTIFY_SETTINGS = Settings.vanotify.services.benefits_management_tools
# The following retry counts each used to be 16, which was causing production strain and staging strain.
# Controls the sidekiq (infrastructure level) retry when the letter ready email job fails.
SIDEKIQ_RETRY_COUNT_FIRST_EMAIL = 5
# Controls the sidekiq (infrastructure level) retry when the letter ready email retry job fails.
SIDEKIQ_RETRY_COUNT_RETRY_EMAIL = 3
# Controls the maximum number of email attempts to VA notify (application level).
MAX_EMAIL_ATTEMPTS = 5
# Controls the sidekiq (infrastructure level) retry when the letter ready push job fails.
SIDEKIQ_RETRY_COUNT_FIRST_PUSH = 5
# Controls the sidekiq (infrastructure level) retry when the letter ready notification job fails.
SIDEKIQ_RETRY_COUNT_FIRST_NOTIFICATION = 5
# Hostname mapping for different environments
HOSTNAME_MAPPING = {
'dev-api.va.gov' => 'dev.va.gov',
'staging-api.va.gov' => 'staging.va.gov',
'api.va.gov' => 'www.va.gov'
}.freeze
# DataDog tags for event bus gateway services
DD_TAGS = [
'service:event-bus-gateway',
'team:cross-benefits-crew',
'team:benefits',
'itportfolio:benefits-delivery',
'dependency:va-notify'
].freeze
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/event_bus_gateway/letter_ready_notification_job.rb
|
# frozen_string_literal: true
require 'sidekiq'
require 'sidekiq/attr_package'
require_relative 'constants'
require_relative 'errors'
require_relative 'letter_ready_job_concern'
require_relative 'letter_ready_email_job'
require_relative 'letter_ready_push_job'
module EventBusGateway
class LetterReadyNotificationJob
include Sidekiq::Job
include LetterReadyJobConcern
STATSD_METRIC_PREFIX = 'event_bus_gateway.letter_ready_notification'
sidekiq_options retry: Constants::SIDEKIQ_RETRY_COUNT_FIRST_NOTIFICATION
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
::Rails.logger.error('LetterReadyNotificationJob retries exhausted',
{ job_id:, timestamp:, error_class:, error_message: })
tags = Constants::DD_TAGS + ["function: #{error_message}"]
StatsD.increment("#{STATSD_METRIC_PREFIX}.exhausted", tags:)
end
def perform(participant_id, email_template_id = nil, push_template_id = nil)
# Fetch participant data upfront
icn = get_icn(participant_id)
errors = []
errors << handle_email_notification(participant_id, email_template_id, icn)
errors << handle_push_notification(participant_id, push_template_id, icn)
errors.compact!
log_completion(email_template_id, push_template_id, errors)
handle_errors(errors)
errors
rescue => e
# Only catch errors from the initial BGS/MPI lookups
if e.is_a?(Errors::BgsPersonNotFoundError) ||
e.is_a?(Errors::MpiProfileNotFoundError) ||
@bgs_person.nil? || @mpi_profile.nil?
record_notification_send_failure(e, 'Notification')
end
raise
end
private
def should_send_email?(email_template_id, icn)
email_template_id.present? && icn.present?
end
def should_send_push?(push_template_id, icn)
push_template_id.present? && icn.present?
end
def handle_email_notification(participant_id, email_template_id, icn)
if should_send_email?(email_template_id, icn)
first_name = get_first_name_from_participant_id(participant_id)
if first_name.present?
send_email_async(participant_id, email_template_id, first_name, icn)
else
log_notification_skipped('email', 'first_name not present', email_template_id)
nil
end
else
log_notification_skipped('email', 'ICN or template not available', email_template_id)
nil
end
end
def handle_push_notification(participant_id, push_template_id, icn)
unless should_send_push?(push_template_id, icn)
log_notification_skipped('push', 'ICN or template not available', push_template_id)
return nil
end
unless Flipper.enabled?(:event_bus_gateway_letter_ready_push_notifications, Flipper::Actor.new(icn))
log_notification_skipped('push', 'Push notifications not enabled for this user', push_template_id)
return nil
end
send_push_async(participant_id, push_template_id, icn)
end
def send_email_async(participant_id, email_template_id, first_name, icn)
# Store PII in Redis and pass only cache key to avoid PII exposure in logs
cache_key = Sidekiq::AttrPackage.create(first_name:, icn:)
LetterReadyEmailJob.perform_async(participant_id, email_template_id, cache_key)
nil
rescue => e
log_notification_failure('email', email_template_id, e)
{ type: 'email', error: e.message }
end
def send_push_async(participant_id, push_template_id, icn)
# Store PII in Redis and pass only cache key to avoid PII exposure in logs
cache_key = Sidekiq::AttrPackage.create(icn:)
LetterReadyPushJob.perform_async(participant_id, push_template_id, cache_key)
nil
rescue => e
log_notification_failure('push', push_template_id, e)
{ type: 'push', error: e.message }
end
def log_notification_failure(notification_type, template_id, error)
::Rails.logger.error(
"LetterReadyNotificationJob #{notification_type} enqueue failed",
{
notification_type:,
template_id:,
error_class: error.class.name,
error_message: error.message
}
)
# Track enqueuing failures (different from send failures tracked in child jobs)
tags = Constants::DD_TAGS + [
"notification_type:#{notification_type}",
"error:#{error.class.name}"
]
StatsD.increment("#{STATSD_METRIC_PREFIX}.enqueue_failure", tags:)
end
def log_notification_skipped(notification_type, reason, template_id)
::Rails.logger.error(
"LetterReadyNotificationJob #{notification_type} skipped",
{
notification_type:,
reason:,
template_id:
}
)
tags = Constants::DD_TAGS + [
"notification_type:#{notification_type}",
"reason:#{reason.parameterize.underscore}"
]
StatsD.increment("#{STATSD_METRIC_PREFIX}.skipped", tags:)
end
def log_completion(email_template_id, push_template_id, errors)
successful_notifications = []
successful_notifications << 'email' if email_template_id.present? && errors.none? { |e| e[:type] == 'email' }
successful_notifications << 'push' if push_template_id.present? && errors.none? { |e| e[:type] == 'push' }
failed_messages = errors.map { |h| "#{h[:type]}: #{h[:error]}" }.join(', ')
::Rails.logger.info(
'LetterReadyNotificationJob completed',
{
notifications_sent: successful_notifications.join(', '),
notifications_failed: failed_messages,
email_template_id:,
push_template_id:
}
)
end
def handle_errors(errors)
return if errors.empty?
if errors.length == 2
# Both notifications failed to enqueue
error_details = errors.map { |e| "#{e[:type]}: #{e[:error]}" }.join('; ')
raise Errors::NotificationEnqueueError, "All notifications failed to enqueue: #{error_details}"
else
# Partial failure - determine which notification succeeded
successful = errors[0][:type] == 'email' ? 'push' : 'email'
error_messages = errors.map { |h| "#{h[:type]}: #{h[:error]}" }.join(', ')
::Rails.logger.warn(
'LetterReadyNotificationJob partial failure',
{
successful:,
failed: error_messages
}
)
end
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/event_bus_gateway/letter_ready_retry_email_job.rb
|
# frozen_string_literal: true
require 'sidekiq'
require_relative 'constants'
module EventBusGateway
class LetterReadyRetryEmailJob
include Sidekiq::Job
class EventBusGatewayNotificationNotFoundError < StandardError; end
STATSD_METRIC_PREFIX = 'event_bus_gateway.letter_ready_retry_email'
sidekiq_options retry: Constants::SIDEKIQ_RETRY_COUNT_RETRY_EMAIL
sidekiq_retries_exhausted do |msg, _ex|
job_id = msg['jid']
error_class = msg['error_class']
error_message = msg['error_message']
timestamp = Time.now.utc
::Rails.logger.error('LetterReadyRetryEmailJob retries exhausted',
{ job_id:, timestamp:, error_class:, error_message: })
StatsD.increment("#{STATSD_METRIC_PREFIX}.exhausted", tags: Constants::DD_TAGS)
end
def perform(participant_id, template_id, personalisation, notification_id)
original_notification = EventBusGatewayNotification.find_by(id: notification_id)
raise EventBusGatewayNotificationNotFoundError if original_notification.nil?
response = notify_client.send_email(
recipient_identifier: { id_value: participant_id, id_type: 'PID' },
template_id:,
personalisation:
)
increment_attempts_counter(original_notification, response.id)
StatsD.increment("#{STATSD_METRIC_PREFIX}.success", tags: Constants::DD_TAGS)
rescue => e
record_email_send_failure(e)
raise
end
private
def notify_client
@notify_client ||= VaNotify::Service.new(Constants::NOTIFY_SETTINGS.api_key,
{ callback_klass: 'EventBusGateway::VANotifyEmailStatusCallback' })
end
def increment_attempts_counter(original_notification, new_va_notify_id)
original_notification.update!(
attempts: original_notification.attempts + 1,
va_notify_id: new_va_notify_id
)
end
def record_email_send_failure(error)
error_message = 'LetterReadyRetryEmailJob email error'
::Rails.logger.error(error_message, { message: error.message })
tags = Constants::DD_TAGS + ["function: #{error_message}"]
StatsD.increment("#{STATSD_METRIC_PREFIX}.failure", tags:)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/schema_contract/validation_job.rb
|
# frozen_string_literal: true
module SchemaContract
class ValidationJob
include Sidekiq::Job
sidekiq_options(retry: false)
def perform(contract_name)
SchemaContract::Validator.new(contract_name).validate
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/schema_contract/delete_validation_records_job.rb
|
# frozen_string_literal: true
module SchemaContract
class DeleteValidationRecordsJob
include Sidekiq::Job
sidekiq_options(retry: false)
def perform
SchemaContract::Validation.where(updated_at: ..1.month.ago).destroy_all
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/form1010cg/delete_old_uploads_job.rb
|
# frozen_string_literal: true
# DeleteOldUploadsJob
#
# This Sidekiq job deletes expired 10-10CG (Caregiver Assistance) form uploads from storage.
# It helps manage storage usage and ensures that old, unused attachments are removed.
#
# Why:
# - Prevents accumulation of unused or expired uploads, reducing storage costs and clutter.
# - Supports privacy and security by removing attachments that are no longer needed.
#
# How:
# - Identifies uploads older than the configured expiration time (defined by EXPIRATION_TIME).
# - Deletes expired attachments for the Caregiver Assistance form.
# - Can be extended to support additional attachment classes or forms if needed.
module Form1010cg
class DeleteOldUploadsJob < DeleteAttachmentJob
ATTACHMENT_CLASSES = [Form1010cg::Attachment.name].freeze
FORM_ID = SavedClaim::CaregiversAssistanceClaim::FORM
EXPIRATION_TIME = 30.days
def uuids_to_keep
[]
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/form1010cg/submission_job.rb
|
# frozen_string_literal: true
# SubmissionJob
#
# This Sidekiq job processes and submits 10-10CG (Caregiver Assistance) claims to the CARMA backend.
# It manages the full lifecycle of a claim submission, including error handling, logging, and notification.
#
# Why:
# - Automates the asynchronous submission of caregiver claims, improving reliability and scalability.
# - Ensures claims are processed even if the web request fails or times out.
# - Provides robust error handling, retry logic, and user notification on failure.
#
# How:
# - Loads the claim by ID and processes it using Form1010cg::Service.
# - Destroys the claim after successful processing to prevent duplicate submissions.
# - Handles and logs errors, including parsing errors from CARMA and general exceptions.
# - Sends failure notification emails to users if submission fails after all retries.
# - Tracks job metrics and durations for monitoring and analytics.
require 'sidekiq/monitored_worker'
module Form1010cg
class SubmissionJob
STATSD_KEY_PREFIX = "#{Form1010cg::Auditor::STATSD_KEY_PREFIX}.async.".freeze
DD_ZSF_TAGS = [
'service:caregiver-application',
'function: 10-10CG async form submission'
].freeze
CALLBACK_METADATA = {
callback_metadata: {
notification_type: 'error',
form_number: '10-10CG',
statsd_tags: DD_ZSF_TAGS
}
}.freeze
include Sidekiq::Job
include Sidekiq::MonitoredWorker
# retry for 2d 1h 47m 12s
# https://github.com/sidekiq/sidekiq/wiki/Error-Handling
sidekiq_options retry: 16
sidekiq_retries_exhausted do |msg, _e|
claim_id = msg['args'][0]
StatsD.increment("#{STATSD_KEY_PREFIX}failed_no_retries_left", tags: ["claim_id:#{claim_id}"])
claim = SavedClaim::CaregiversAssistanceClaim.find(claim_id)
send_failure_email(claim)
end
def retry_limits_for_notification
[1, 10]
end
def notify(params)
# Add 1 to retry_count to match retry_monitoring logic
retry_count = Integer(params['retry_count']) + 1
claim_id = params['args'][0]
StatsD.increment("#{STATSD_KEY_PREFIX}applications_retried") if retry_count == 1
if retry_count == 10
StatsD.increment("#{STATSD_KEY_PREFIX}failed_ten_retries",
tags: ["params:#{params}", "claim_id:#{claim_id}"])
end
end
def perform(claim_id)
start_time = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
claim = SavedClaim::CaregiversAssistanceClaim.find(claim_id)
Form1010cg::Service.new(claim).process_claim_v2!
begin
claim.destroy!
rescue => e
log_error(e, '[10-10CG] - Error destroying Caregiver claim after processing submission in job', claim_id)
end
Form1010cg::Auditor.new.log_caregiver_request_duration(context: :process_job, event: :success, start_time:)
rescue CARMA::Client::MuleSoftClient::RecordParseError
StatsD.increment("#{STATSD_KEY_PREFIX}record_parse_error", tags: ["claim_id:#{claim_id}"])
Form1010cg::Auditor.new.log_caregiver_request_duration(context: :process_job, event: :failure, start_time:)
self.class.send_failure_email(claim)
rescue => e
log_error(e, '[10-10CG] - Error processing Caregiver claim submission in job', claim_id)
StatsD.increment("#{STATSD_KEY_PREFIX}retries")
Form1010cg::Auditor.new.log_caregiver_request_duration(context: :process_job, event: :failure, start_time:)
raise
end
class << self
def send_failure_email(claim)
unless claim.parsed_form.dig('veteran', 'email')
StatsD.increment('silent_failure', tags: DD_ZSF_TAGS)
return
end
parsed_form = claim.parsed_form
first_name = parsed_form.dig('veteran', 'fullName', 'first')
email = parsed_form.dig('veteran', 'email')
template_id = Settings.vanotify.services.health_apps_1010.template_id.form1010_cg_failure_email
api_key = Settings.vanotify.services.health_apps_1010.api_key
salutation = first_name ? "Dear #{first_name}," : ''
VANotify::EmailJob.perform_async(
email,
template_id,
{ 'salutation' => salutation },
api_key,
CALLBACK_METADATA
)
StatsD.increment("#{STATSD_KEY_PREFIX}submission_failure_email_sent", tags: ["claim_id:#{claim.id}"])
end
end
private
def log_error(exception, message, claim_id)
Rails.logger.error(message, { exception:, claim_id: })
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/terms_of_use/sign_up_service_updater_job.rb
|
# frozen_string_literal: true
require 'map/sign_up/service'
require 'sidekiq/attr_package'
module TermsOfUse
class SignUpServiceUpdaterJob
include Sidekiq::Job
LOG_TITLE = '[TermsOfUse][SignUpServiceUpdaterJob]'
sidekiq_options retry_for: 48.hours
sidekiq_retries_exhausted do |job, exception|
user_account = UserAccount.find_by(id: job['args'].first)
version = job['args'].second
agreement = user_account.terms_of_use_agreements.where(agreement_version: version).last if user_account.present?
payload = {
icn: user_account&.icn,
version:,
response: agreement&.response,
response_time: agreement&.created_at&.iso8601,
exception_message: exception.message
}
Rails.logger.warn("#{LOG_TITLE} retries exhausted", payload)
end
attr_reader :user_account_uuid, :version
def perform(user_account_uuid, version)
@user_account_uuid = user_account_uuid
@version = version
return if missing_sec_id? || agreement_unchanged?
log_updated_icn
terms_of_use_agreement.accepted? ? accept : decline
end
private
def log_updated_icn
if user_account.icn != mpi_profile.icn
Rails.logger.info("#{LOG_TITLE} Detected changed ICN for user",
{ icn: user_account.icn, mpi_icn: mpi_profile.icn })
end
end
def map_client
@map_client ||= MAP::SignUp::Service.new
end
def map_status
@map_status ||= map_client.status(icn: mpi_profile.icn)
end
def agreement_unchanged?
if terms_of_use_agreement.declined? != map_status[:opt_out] ||
terms_of_use_agreement.accepted? != map_status[:agreement_signed]
return false
end
Rails.logger.info("#{LOG_TITLE} Not updating Sign Up Service due to unchanged agreement",
{ icn: user_account.icn })
true
end
def accept
map_client.agreements_accept(icn: mpi_profile.icn, signature_name:, version:)
end
def decline
map_client.agreements_decline(icn: mpi_profile.icn)
end
def missing_sec_id?
if mpi_profile.sec_id.present?
validate_multiple_sec_ids
return false
end
Rails.logger.info("#{LOG_TITLE} Sign Up Service not updated due to user missing sec_id",
{ icn: user_account.icn })
true
end
def validate_multiple_sec_ids
if mpi_profile.sec_ids.many?
Rails.logger.info("#{LOG_TITLE} Multiple sec_id values detected", { icn: user_account.icn })
end
end
def user_account
@user_account ||= UserAccount.find(user_account_uuid)
end
def terms_of_use_agreement
user_account.terms_of_use_agreements.where(agreement_version: version).last
end
def signature_name
"#{mpi_profile.given_names.first} #{mpi_profile.family_name}"
end
def mpi_profile
@mpi_profile ||= MPI::Service.new.find_profile_by_identifier(identifier: user_account.icn,
identifier_type: MPI::Constants::ICN)&.profile
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/create10203_spool_submissions_report.rb
|
# frozen_string_literal: true
module EducationForm
class Create10203SpoolSubmissionsReport
require 'csv'
include Sidekiq::Job
def format_name(full_name)
return if full_name.blank?
[full_name['first'], full_name['last']].compact.join(' ')
end
def processed_at_range
(@time - 24.hours)..@time
end
def denied(state)
denied?(state) ? 'Y' : 'N'
end
def denied?(state)
state == 'denied'
end
def poa?(poa)
return '' if poa.nil?
poa ? 'Y' : 'N'
end
def create_csv_array
data = {
csv_array: []
}
header_row(data)
submissions = processed_submissions
denial_count = 0
submissions.find_each do |education_benefits_claim|
automated_decision_state = education_benefits_claim.education_stem_automated_decision&.automated_decision_state
denial_count += 1 if denied?(automated_decision_state)
data[:csv_array] << row(education_benefits_claim)
end
# Totals row
data[:csv_array] << ['Total Submissions and Denials', '', '', '', submissions.count, denial_count, '']
data
end
def header_row(data)
data[:csv_array] << ['Submitted VA.gov Applications - Report YYYY-MM-DD', 'Claimant Name',
'Veteran Name', 'Confirmation #', 'Time Submitted', 'Denied (Y/N)',
'POA (Y/N)', 'RPO']
data
end
def processed_submissions
EducationBenefitsClaim.includes(:saved_claim, :education_stem_automated_decision).where(
processed_at: processed_at_range,
saved_claims: {
form_id: '22-10203'
}
)
end
def row(ebc)
parsed_form = ebc.parsed_form
['',
format_name(parsed_form['relativeFullName']),
format_name(parsed_form['veteranFullName']),
ebc.confirmation_number,
ebc.processed_at.to_s,
denied(ebc.education_stem_automated_decision&.automated_decision_state),
poa?(ebc.education_stem_automated_decision&.poa),
ebc.regional_processing_office]
end
def perform
@time = Time.zone.now
folder = 'tmp/spool10203_reports'
FileUtils.mkdir_p(folder)
filename = "#{folder}/#{@time.to_date}.csv"
csv_array_data = create_csv_array
csv_array = csv_array_data[:csv_array]
CSV.open(filename, 'wb') do |csv|
csv_array.each do |row|
csv << row
end
end
return false unless FeatureFlipper.send_edu_report_email?
Spool10203SubmissionsReportMailer.build(filename).deliver_now
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/create_daily_fiscal_year_to_date_report.rb
|
# frozen_string_literal: true
module EducationForm
class CreateDailyFiscalYearToDateReport
include Sidekiq::Job
require 'csv'
sidekiq_options(unique_for: 30.minutes)
TOTALS_HASH = {
yearly: 0,
daily_submitted: 0,
daily_processed: 0
}.freeze
FORM_TYPES = EducationBenefitsClaim::FORM_TYPES.reject do |form_type|
%w[10282 10216 10215 10297 1919 0839 10275 8794 0976 1990e 0803].include?(form_type)
end.freeze
FORM_TYPE_HEADERS = EducationBenefitsClaim.form_headers(FORM_TYPES).map do |form_header|
[form_header, '', '']
end.flatten.freeze
OCTOBER = 10
# use yesterday as the date for the daily job otherwise we will
# miss applications that are submitted after the report is run
def initialize(date = yesterday)
@date = date
end
def yesterday
Time.zone.today - 1.day
end
def beginning_of_fiscal_year
# The beginning of the federal fiscal year is October 1st
Date.new(fiscal_year - 1, OCTOBER)
end
def fiscal_year
if @date.month < OCTOBER
@date.year
else
@date.year + 1
end
end
def build_submission_relation(range_type, region, form_type, status)
range = @ranges[range_type]
relation = EducationBenefitsSubmission.where(
created_at: range,
region: region.to_s,
form_type:
)
relation = relation.where(status: 'processed') if status == :processed
relation
end
def show_individual_benefits(form_type)
%w[0993].exclude?(form_type)
end
def calculate_submissions(range_type: :year, status: :processed)
submissions = {}
application_types = EducationBenefitsClaim::APPLICATION_TYPES
FORM_TYPES.each do |form_type|
form_submissions = {}
EducationFacility::REGIONS.each do |region|
next if region_excluded(fiscal_year, region)
relation = build_submission_relation(range_type, region, form_type, status)
form_submissions[region] = build_region_submission(application_types, form_type, relation)
end
submissions[form_type] = form_submissions
end
submissions
end
def build_region_submission(application_types, form_type, relation)
region_submissions = {}
if show_individual_benefits(form_type)
application_types.each do |application_type|
region_submissions[application_type] = relation.where(application_type => true).count
end
else
region_submissions[:all] = relation.count
end
region_submissions
end
def create_csv_header
csv_array = []
num_form_types = FORM_TYPES.size
@ranges = {
day: @date.all_day,
year: beginning_of_fiscal_year..@date.end_of_day
}
ranges_header = [@ranges[:year].to_s, '', @ranges[:day].to_s]
submitted_header = ['', 'Submitted', 'Sent to Spool File']
csv_array << ["Submitted Vets.gov Applications - Report FYTD #{fiscal_year} as of #{@date}"]
csv_array << ['', '', 'DOCUMENT TYPE']
csv_array << (['RPO', 'BENEFIT TYPE'] + FORM_TYPE_HEADERS)
csv_array << (['', ''] + (ranges_header * num_form_types))
csv_array << (['', ''] + (submitted_header * num_form_types))
csv_array
end
def create_data_row(on_last_index, application_type, region, submissions, submissions_total)
row = []
FORM_TYPES.each do |form_type|
next row += ['', '', ''] if !show_individual_benefits(form_type) && !on_last_index
TOTALS_HASH.each_key do |range_type|
application_type_key = show_individual_benefits(form_type) ? application_type : :all
num_submissions = submissions[range_type][form_type][region][application_type_key]
row << num_submissions
submissions_total[form_type][range_type] += num_submissions
end
end
row
end
def create_csv_data_block(region, submissions, submissions_total)
csv_array = []
application_types = EducationBenefitsClaim::APPLICATION_TYPES
application_types.each_with_index do |application_type, i|
on_last_index = i == (application_types.size - 1)
row = [
i.zero? ? EducationFacility::RPO_NAMES[region] : '',
application_type.humanize(capitalize: false)
]
row += create_data_row(
on_last_index,
application_type,
region,
submissions,
submissions_total
)
csv_array << row
end
csv_array
end
def create_totals_row(text_rows, totals)
row = text_rows.clone
FORM_TYPES.each do |form_type|
TOTALS_HASH.each_key do |range_type|
row << totals[form_type][range_type]
end
end
row
end
def get_totals_hash_with_form_types
totals = {}
FORM_TYPES.each do |form_type|
totals[form_type] = TOTALS_HASH.dup
end
totals
end
def convert_submissions_to_csv_array
submissions_csv_array = []
submissions = {
yearly: calculate_submissions,
daily_submitted: calculate_submissions(range_type: :day, status: :submitted),
daily_processed: calculate_submissions(range_type: :day, status: :processed)
}
grand_totals = get_totals_hash_with_form_types
EducationFacility::REGIONS.each do |region|
next if region_excluded(fiscal_year, region)
submissions_total = get_totals_hash_with_form_types
submissions_csv_array += create_csv_data_block(region, submissions, submissions_total)
submissions_csv_array << create_totals_row(['', 'TOTAL'], submissions_total)
submissions_total.each do |form_type, form_submissions|
form_submissions.each do |range_type, total|
grand_totals[form_type][range_type] += total
end
end
end
submissions_csv_array << create_totals_row(['ALL RPOS TOTAL', ''], grand_totals)
submissions_csv_array
end
def region_excluded(fiscal_year, region)
# Atlanta is to be excluded from FYTD reports after the 2017 fiscal year
return true if fiscal_year > 2017 && region == :southern
# St. Louis is to be excluded from FYTD reports after the 2020 fiscal year
return true if fiscal_year > 2020 && region == :central
false
end
def create_csv_array
csv_array = []
csv_array += create_csv_header
csv_array += convert_submissions_to_csv_array
csv_array << (['', ''] + FORM_TYPE_HEADERS)
csv_array
end
def generate_csv
folder = 'tmp/daily_reports'
FileUtils.mkdir_p(folder)
filename = "#{folder}/#{@date}.csv"
CSV.open(filename, 'wb') do |csv|
create_csv_array.each do |row|
csv << row
end
end
filename
end
def perform
filename = generate_csv
return unless FeatureFlipper.send_edu_report_email?
YearToDateReportMailer.build(filename).deliver_now
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/create_daily_spool_files.rb
|
# frozen_string_literal: true
require 'net/sftp'
require 'vets/shared_logging'
require 'sftp_writer/factory'
module EducationForm
class FormattingError < StandardError
end
class DailySpoolFileError < StandardError
end
class CreateDailySpoolFiles
MAX_RETRIES = 5
WINDOWS_NOTEPAD_LINEBREAK = "\r\n"
STATSD_KEY = 'worker.education_benefits_claim'
STATSD_FAILURE_METRIC = "#{STATSD_KEY}.failed_spool_file".freeze
LIVE_FORM_TYPES = %w[1990 1995 5490 5495 0993 0994 10203 10297].map do |t|
"22-#{t.upcase}"
end.freeze
AUTOMATED_DECISIONS_STATES = [nil, 'denied', 'processed'].freeze
include Sidekiq::Job
include Vets::SharedLogging
sidekiq_options queue: 'default',
unique_for: 30.minutes,
retry: 5
# Setting the default value to the `unprocessed` scope is safe
# because the execution of the query itself is deferred until the
# data is accessed by the code inside of the method.
def perform
retry_count = 0
begin
records = EducationBenefitsClaim
.unprocessed.joins(:saved_claim).includes(:education_stem_automated_decision).where(
saved_claims: {
form_id: LIVE_FORM_TYPES
},
education_stem_automated_decisions: { automated_decision_state: AUTOMATED_DECISIONS_STATES }
)
return false if federal_holiday?
if records.count.zero?
log_info('No records to process.')
return true
elsif retry_count.zero?
log_info("Processing #{records.count} application(s)")
end
# Group the formatted records into different regions
regional_data = group_submissions_by_region(records)
formatted_records = format_records(regional_data)
# Create a remote file for each region, and write the records into them
writer = SFTPWriter::Factory.get_writer(Settings.edu.sftp).new(Settings.edu.sftp, logger:)
write_files(writer, structured_data: formatted_records)
rescue => e
StatsD.increment("#{STATSD_FAILURE_METRIC}.general")
if retry_count < MAX_RETRIES
log_exception(DailySpoolFileError.new("Error creating spool files.\n\n#{e}
Retry count: #{retry_count}. Retrying..... "))
retry_count += 1
sleep(10 * retry_count) # exponential backoff for retries
retry
else
log_exception(DailySpoolFileError.new("Error creating spool files.
Job failed after #{MAX_RETRIES} retries \n\n#{e}"))
end
end
true
end
def group_submissions_by_region(records)
records.group_by { |r| r.regional_processing_office.to_sym }
end
# Convert the records into instances of their form representation.
# The conversion into 'spool file format' takes place here, rather
# than when we're writing the files so we can hold the connection
# open for a shorter period of time.
def format_records(grouped_data)
raw_groups = grouped_data.each do |region, v|
region_id = EducationFacility.facility_for(region:)
grouped_data[region] = v.map do |record|
format_application(record, rpo: region_id)
end.compact
end
# delete any regions that only had malformed claims before returning
raw_groups.delete_if { |_, v| v.empty? }
end
# Write out the combined spool files for each region along with recording
# and tracking successful transfers.
# Creates or updates an SpoolFileEvent for tracking and to prevent multiple files per RPO per date during retries
def write_files(writer, structured_data:)
structured_data.each do |region, records|
region_id = EducationFacility.facility_for(region:)
filename = "#{region_id}_#{Time.zone.now.strftime('%m%d%Y_%H%M%S')}_vetsgov.spl"
spool_file_event = SpoolFileEvent.build_event(region_id, filename)
if spool_file_event.successful_at.present?
log_info("A spool file for #{region_id} on #{Time.zone.now.strftime('%m%d%Y')} was already created")
else
log_submissions(records, filename, region)
# create the single textual spool file
contents = records.map(&:text).join(EducationForm::CreateDailySpoolFiles::WINDOWS_NOTEPAD_LINEBREAK)
begin
log_info("Uploading #{contents.size} bytes to region: #{region}") if Settings.hostname.eql?('api.va.gov')
bytes_sent = writer.write(contents, filename)
if bytes_sent.eql?(contents.size) && Settings.hostname.eql?('api.va.gov')
log_info("Successfully uploaded #{bytes_sent} bytes to region: #{region}")
elsif Settings.hostname.eql?('api.va.gov')
log_info("Warning: Uploaded #{bytes_sent} bytes to region: #{region}")
end
## Testing to see if writer is the cause for retry attempt failures
## If we get to this message, it's not the writer object
log_info("Successfully wrote #{records.count} applications to filename: #{filename} for region: #{region}")
# send copy of staging spool files to testers
# This mailer is intended to only work for development, staging and NOT production
# Rails.env will return 'production' on the development & staging servers and which
# will trip the unwary. To be safe, use Settings.hostname
email_staging_spool_files(contents) if local_or_staging_env?
# track and update the records as processed once the file has been successfully written
track_submissions(region_id)
records.each { |r| r.record.update(processed_at: Time.zone.now) }
spool_file_event.update(number_of_submissions: records.count, successful_at: Time.zone.now)
rescue => e
StatsD.increment("#{STATSD_FAILURE_METRIC}.#{region_id}")
attempt_msg = if spool_file_event.retry_attempt.zero?
'initial attempt'
else
"attempt #{spool_file_event.retry_attempt}"
end
exception = DailySpoolFileError.new("Error creating #{filename} during #{attempt_msg}.\n\n#{e}")
log_exception(exception, region)
if spool_file_event.retry_attempt < MAX_RETRIES
spool_file_event.update(retry_attempt: spool_file_event.retry_attempt + 1)
# Reinstantiate the writer before retrying
writer = SFTPWriter::Factory.get_writer(Settings.edu.sftp).new(Settings.edu.sftp, logger:)
retry
else
next
end
end
end
end
ensure
writer.close
end
# Previously there was data.saved_claim.valid? check but this was causing issues for forms when
# 1. on submission the submission data is validated against vets-json-schema
# 2. vets-json-schema is updated in vets-api
# 3. during spool file creation the schema is then again validated against vets-json-schema
# 4. submission is no longer valid due to changes in step 2
def format_application(data, rpo: 0)
form = EducationForm::Forms::Base.build(data)
track_form_type("22-#{data.form_type}", rpo)
form
rescue => e
inform_on_error(data, rpo, e)
nil
end
def inform_on_error(claim, region, error = nil)
StatsD.increment("#{STATSD_KEY}.failed_formatting.#{region}.22-#{claim.form_type}")
exception = if error.present?
FormattingError.new("Could not format #{claim.confirmation_number}.\n\n#{error}")
else
FormattingError.new("Could not format #{claim.confirmation_number}")
end
log_exception(exception, nil, send_email: false)
end
private
def federal_holiday?
holiday = Holidays.on(Time.zone.today, :us, :observed)
if holiday.empty?
false
else
log_info("Skipping on a Holiday: #{holiday.first[:name]}")
true
end
end
# Useful for debugging which records were or were not sent over successfully,
# in case of network failures.
def log_submissions(records, filename, region)
log_info("Writing #{records.count} application(s) to #{filename} for region: #{region}")
end
# Useful for alerting and monitoring the numbers of successfully send submissions
# per-rpo, rather than the number of records that were *prepared* to be sent.
def track_submissions(region_id)
stats[region_id].each do |type, count|
StatsD.gauge("#{STATSD_KEY}.transmissions.#{region_id}.#{type}", count)
end
end
def track_form_type(type, rpo)
stats[rpo][type] += 1
end
def stats
@stats ||= Hash.new(Hash.new(0))
end
def log_exception(exception, region = nil, send_email: true)
log_exception_to_sentry(exception)
log_exception_to_rails(exception)
log_to_slack(exception.to_s)
log_to_email(region) if send_email
end
def log_info(message)
logger.info(message)
log_to_slack(message)
end
def log_to_slack(message)
return unless Flipper.enabled?(:spool_testing_error_2)
client = SlackNotify::Client.new(webhook_url: Settings.edu.slack.webhook_url,
channel: '#vsa-education-logs',
username: "#{self.class.name} - #{Settings.vsp_environment}")
client.notify(message)
end
def log_to_email(region)
return unless Flipper.enabled?(:spool_testing_error_3) && !FeatureFlipper.staging_email?
CreateDailySpoolFilesMailer.build(region).deliver_now
end
def email_staging_spool_files(contents)
CreateStagingSpoolFilesMailer.build(contents).deliver_now
end
def local_or_staging_env?
Rails.env.eql?('development') || Settings.hostname.eql?('staging-api.va.gov')
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/send_school_certifying_officials_email.rb
|
# frozen_string_literal: true
require 'gi/client'
module EducationForm
class SendSchoolCertifyingOfficialsEmail
include Sidekiq::Job
def perform(claim_id, less_than_six_months, facility_code)
@claim = SavedClaim::EducationBenefits::VA10203.find(claim_id)
@claim.email_sent(false)
if less_than_six_months && facility_code.present?
@institution = get_institution(facility_code)
send_sco_email
end
end
def self.sco_emails(scos)
emails = []
primary = scos.find { |sco| sco[:priority] == 'Primary' && sco[:email].present? }
secondary = scos.find { |sco| sco[:priority] == 'Secondary' && sco[:email].present? }
emails.push(primary[:email]) if primary.present?
emails.push(secondary[:email]) if secondary.present?
emails
end
private
def get_institution(facility_code)
GI::Client.new.get_institution_details_v0({ id: facility_code }).body[:data][:attributes]
rescue Common::Exceptions::RecordNotFound
StatsD.increment("#{stats_key}.skipped.institution_not_approved")
nil
end
def school_changed?
application = @claim.parsed_form
form_school_name = application['schoolName']
form_school_city = application['schoolCity']
form_school_state = application['schoolState']
prefill_name = @institution[:name]
prefill_city = @institution[:city]
prefill_state = @institution[:state]
form_school_name != prefill_name ||
form_school_city != prefill_city ||
form_school_state != prefill_state
end
def send_sco_email
return if @institution.blank? || school_changed?
emails = recipients
if emails.any?
StatsD.increment("#{stats_key}.success")
SchoolCertifyingOfficialsMailer.build(@claim.id, emails, nil).deliver_now
StemApplicantScoMailer.build(@claim.id, nil).deliver_now
@claim.email_sent(true)
else
StatsD.increment("#{stats_key}.failure")
end
end
def recipients
scos = @institution[:versioned_school_certifying_officials]
EducationForm::SendSchoolCertifyingOfficialsEmail.sco_emails(scos)
end
def stats_key
'api.education_benefits_claim.22-10203.school_certifying_officials_mailer'
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/process10203_submissions.rb
|
# frozen_string_literal: true
require 'vets/shared_logging'
module EducationForm
class FormattingError < StandardError
end
class Process10203EVSSError < StandardError
end
class Process10203Submissions
include Sidekiq::Job
include Vets::SharedLogging
sidekiq_options queue: 'default', backtrace: true, unique_for: 24.hours
# Get all 10203 submissions that have a row in education_stem_automated_decisions
def perform(
records: EducationBenefitsClaim.joins(:education_stem_automated_decision).includes(:saved_claim).where(
saved_claims: {
form_id: '22-10203'
}
).order('education_benefits_claims.created_at')
)
init_count = records.filter do |r|
r.education_stem_automated_decision.automated_decision_state == EducationStemAutomatedDecision::INIT
end.count
if init_count.zero?
log_info('No records with init status to process.')
return true
else
log_info("Processing #{init_count} application(s) with init status")
end
user_submissions = group_user_uuid(records)
process_user_submissions(user_submissions)
end
private
# Group the submissions by user_uuid
def group_user_uuid(records)
records.group_by { |ebc| ebc.education_stem_automated_decision&.user_uuid }
end
# If there are multiple submissions for a user compare un-submitted to most recent processed
# by EducationForm::CreateDailySpoolFiles
# Otherwise check submission data and EVSS data to see if submission can be marked as PROCESSED
def process_user_submissions(user_submissions)
user_submissions.each_value do |submissions|
auth_headers = submissions.last.education_stem_automated_decision.auth_headers
claim_ids = submissions.map(&:id).join(', ')
log_info "EDIPI available for process STEM claim ids=#{claim_ids}: #{auth_headers&.key?('va_eauth_dodedipnid')}"
poa = submissions.last.education_stem_automated_decision.poa
if submissions.count > 1
check_previous_submissions(submissions, poa)
else
process_submission(submissions.first, poa)
end
end
end
# Ignore already processed either by CreateDailySpoolFiles or this job
def update_automated_decision(submission, status, poa)
if submission.processed_at.nil? &&
submission.education_stem_automated_decision&.automated_decision_state == EducationStemAutomatedDecision::INIT
submission.education_stem_automated_decision.update(
automated_decision_state: status,
poa:
)
end
end
# Makes a list of all submissions that have not been processed and have a status of INIT
# Finds most recent submission that has already been processed
#
# Submissions are marked as processed in EducationForm::CreateDailySpoolFiles
#
# For each unprocessed submission compare isEnrolledStem, isPursuingTeachingCert, and benefitLeft values
# to most recent processed submissions
# If values are the same set status as PROCESSED
# Otherwise check submission data and EVSS data to see if submission can be marked as PROCESSED
def check_previous_submissions(submissions, user_has_poa)
unprocessed_submissions = submissions.find_all do |ebc|
ebc.processed_at.nil? &&
ebc.education_stem_automated_decision&.automated_decision_state == EducationStemAutomatedDecision::INIT
end
most_recent_processed = submissions.find_all do |ebc|
ebc.processed_at.present? &&
ebc.education_stem_automated_decision&.automated_decision_state != EducationStemAutomatedDecision::INIT
end
.max_by(&:processed_at)
processed_form = format_application(most_recent_processed) if most_recent_processed.present?
unprocessed_submissions.each do |submission|
unprocessed_form = format_application(submission)
if repeat_form?(unprocessed_form, processed_form)
update_automated_decision(submission, EducationStemAutomatedDecision::PROCESSED, user_has_poa)
else
process_submission(submission, user_has_poa)
end
end
end
def repeat_form?(unprocessed_form, processed_form)
processed_form.present? &&
unprocessed_form.enrolled_stem == processed_form.enrolled_stem &&
unprocessed_form.pursuing_teaching_cert == processed_form.pursuing_teaching_cert &&
unprocessed_form.benefit_left == processed_form.benefit_left
end
# If the user doesn't have EVSS data mark the 10203 as PROCESSED
# Set status to DENIED when EVSS data for a user shows there is more than 6 months of remaining_entitlement
#
# This is only checking EVSS data until form questions that affect setting to DENIED have been reviewed
def process_submission(submission, user_has_poa)
remaining_entitlement = submission.education_stem_automated_decision&.remaining_entitlement
# This code will be updated once QA and additional evaluation is completed
status = if Settings.vsp_environment != 'production' && more_than_six_months?(remaining_entitlement)
EducationStemAutomatedDecision::DENIED
else
EducationStemAutomatedDecision::PROCESSED
end
update_automated_decision(submission, status, user_has_poa)
end
def format_application(data)
EducationForm::Forms::VA10203.build(data)
rescue => e
inform_on_error(data, e)
nil
end
def remaining_entitlement_days(remaining_entitlement)
months = remaining_entitlement.months
days = remaining_entitlement.days
(months * 30) + days
end
# Inverse of less than six months check performed in SavedClaim::EducationBenefits::VA10203
def more_than_six_months?(remaining_entitlement)
return false if remaining_entitlement.blank?
remaining_entitlement_days(remaining_entitlement) > 180
end
def inform_on_error(claim, error = nil)
region = EducationFacility.facility_for(region: :eastern)
StatsD.increment("worker.education_benefits_claim.failed_formatting.#{region}.22-#{claim.form_type}")
exception = if error.present?
FormattingError.new("Could not format #{claim.confirmation_number}.\n\n#{error}")
else
FormattingError.new("Could not format #{claim.confirmation_number}")
end
log_exception_to_sentry(exception)
log_exception_to_rails(exception)
end
def log_info(message)
logger.info(message)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/README.md
|
# Education Form Serialization & Submission
* A series of Spool Files are created with applications grouped into regions
* The files are created from individual applications stored in the database for a given day
* The applications are stored in a format that matches the edu-benefits schema in the vets-json-schema repo
* The applications are formatted and concatenated using the 22-1990.erb template
* The file must use windows-style newlines, and have a maximum line length of 78 characters before the newlines
* The generated files are SFTPed to a remote system or systems.
## Testing Locally
If you want to generate spool files locally, you have two options:
* With at least Sidekiq running, run `rake jobs:create_daily_spool_files`
* With a rails console (`bin/rails c`), run `EducationForm::CreateDailySpoolFiles.new.perform`
The files will be written into `tmp/spool_files`, with each regional file starting with the current date.
Important!!! in config/environments/development.rb set config.eager_load = true or the job will NOT run correctly.
## Reprocessing an application
If an application needs to go to a different processing center, we can take the ID and queue it up to be sent over the next time the spool file job runs:
```
application_id = ###
new_region = one of 'eastern', 'western', or 'central'
application = EducationBenefitsClaim.find(application_id)
application.reprocess_at(region)
```
## Rerunning the job for a day (non production only)
As designed, the Daily Spool File Job only runs once a day. To rerun:
* Run `jobs:reset_daily_spool_files_for_today`
* do either of the two options under Testing Locally
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/create_daily_excel_files.rb
|
# frozen_string_literal: true
require 'net/sftp'
require 'vets/shared_logging'
require 'sftp_writer/factory'
module EducationForm
class DailyExcelFileError < StandardError
end
class CreateDailyExcelFiles
MAX_RETRIES = 5
STATSD_KEY = 'worker.education_benefits_claim'
STATSD_FAILURE_METRIC = "#{STATSD_KEY}.failed_excel_file".freeze
LIVE_FORM_TYPES = ['22-10282'].freeze
AUTOMATED_DECISIONS_STATES = [nil, 'denied', 'processed'].freeze
EXCEL_FIELDS = %w[
name
first_name
last_name
military_affiliation
phone_number
email_address
country
state
race_ethnicity
gender
education_level
employment_status
salary
technology_industry
].freeze
HEADERS = ['Name', 'First Name', 'Last Name', 'Select Military Affiliation',
'Phone Number', 'Email Address', 'Country', 'State', 'Race/Ethnicity',
'Gender of Applicant', 'What is your highest level of education?',
'Are you currently employed?', 'What is your current salary?',
'Are you currently working in the technology industry? (If so, please select one)'].freeze
include Sidekiq::Job
include Vets::SharedLogging
sidekiq_options queue: 'default',
unique_for: 30.minutes,
retry: 5
# rubocop:disable Metrics/MethodLength
def perform
return unless Flipper.enabled?(:form_10282_sftp_upload)
retry_count = 0
filename = "22-10282_#{Time.zone.now.strftime('%m%d%Y_%H%M%S')}.csv"
excel_file_event = ExcelFileEvent.build_event(filename)
begin
records = EducationBenefitsClaim
.unprocessed
.joins(:saved_claim)
.where(
saved_claims: {
form_id: LIVE_FORM_TYPES
}
)
return false if federal_holiday?
if records.count.zero?
log_info('No records to process.')
return true
elsif retry_count.zero?
log_info("Processing #{records.count} application(s)")
end
# Format the records and write to CSV file
formatted_records = format_records(records)
write_csv_file(formatted_records, filename)
upload_file_to_sftp(filename)
# Make records processed and add excel file event for rake job
records.each { |r| r.update(processed_at: Time.zone.now) }
excel_file_event.update(number_of_submissions: records.count, successful_at: Time.zone.now)
rescue => e
StatsD.increment("#{STATSD_FAILURE_METRIC}.general")
if retry_count < MAX_RETRIES
log_exception(DailyExcelFileError.new("Error creating excel files.\n\n#{e}
Retry count: #{retry_count}. Retrying..... "))
retry_count += 1
sleep(10 * retry_count) # exponential backoff for retries
retry
else
log_exception(DailyExcelFileError.new("Error creating excel files.
Job failed after #{MAX_RETRIES} retries \n\n#{e}"))
end
end
true
end
def write_csv_file(records, filename)
retry_count = 0
begin
# Generate CSV string content instead of writing to file
csv_contents = CSV.generate do |csv|
# Add headers
csv << HEADERS
# Add data rows
records.each_with_index do |record, index|
log_info("Processing record #{index + 1}: #{record.inspect}")
begin
row_data = EXCEL_FIELDS.map do |field|
value = record.public_send(field)
value.is_a?(Hash) ? value.to_s : value
end
csv << row_data
rescue => e
log_exception(DailyExcelFileError.new("Failed to add row #{index + 1}:\n"))
log_exception(DailyExcelFileError.new("#{e.message}\nRecord: #{record.inspect}"))
next
end
end
end
# Write to file for backup/audit purposes
File.write("tmp/#{filename}", csv_contents)
log_info('Successfully created CSV file')
# Return the CSV contents
csv_contents
rescue => e
StatsD.increment("#{STATSD_FAILURE_METRIC}.general")
log_exception(DailyExcelFileError.new('Error creating CSV files.'))
if retry_count < MAX_RETRIES
log_exception(DailyExcelFileError.new("Retry count: #{retry_count}. Retrying..... "))
retry_count += 1
sleep(5)
retry
else
log_exception(DailyExcelFileError.new("Job failed after #{MAX_RETRIES} retries \n\n#{e}"))
end
end
end
# rubocop:enable Metrics/MethodLength
def format_records(records)
records.map do |record|
format_application(record)
end.compact
end
def format_application(data)
form = EducationForm::Forms::Base.build(data)
track_form_type("22-#{data.form_type}")
form
rescue => e
inform_on_error(data, e)
nil
end
def inform_on_error(claim, error = nil)
StatsD.increment("#{STATSD_KEY}.failed_formatting.22-#{claim.form_type}")
exception = if error.present?
FormattingError.new("Could not format #{claim.confirmation_number}.\n\n#{error}")
else
FormattingError.new("Could not format #{claim.confirmation_number}")
end
log_exception(exception)
end
private
def federal_holiday?
holiday = Holidays.on(Time.zone.today, :us, :observed)
if holiday.empty?
false
else
log_info("Skipping on a Holiday: #{holiday.first[:name]}")
true
end
end
def track_form_type(type)
StatsD.gauge("#{STATSD_KEY}.transmissions.#{type}", 1)
end
def log_exception(exception)
log_exception_to_sentry(exception)
log_exception_to_rails(exception)
end
def log_info(message)
logger.info(message)
end
def upload_file_to_sftp(filename)
log_info('Form 10282 SFTP Upload: Begin')
options = Settings.form_10282.sftp.merge!(allow_staging_uploads: true)
writer = SFTPWriter::Factory.get_writer(options).new(options, logger:)
file_size = File.size("tmp/#{filename}")
bytes_sent = writer.write(File.open("tmp/#{filename}"), filename)
log_info("Form 10282 SFTP Upload: wrote #{bytes_sent} bytes of a #{file_size} byte file")
log_info('Form 10282 SFTP Upload: Complete')
rescue => e
log_exception(DailyExcelFileError.new("Failed SFTP upload: #{e.message}"))
raise
ensure
writer&.close
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/create10203_applicant_decision_letters.rb
|
# frozen_string_literal: true
require 'vets/shared_logging'
module EducationForm
class FormattingError < StandardError
end
class Create10203ApplicantDecisionLetters
include Sidekiq::Job
include Vets::SharedLogging
sidekiq_options queue: 'default',
backtrace: true
# Get all 10203 submissions that have a row in education_stem_automated_decisions
def perform(
records: EducationBenefitsClaim.includes(:saved_claim, :education_stem_automated_decision).where(
saved_claims: {
form_id: '22-10203'
},
education_stem_automated_decisions: {
automated_decision_state: EducationStemAutomatedDecision::DENIED,
denial_email_sent_at: nil
}
)
)
if records.count.zero?
log_info('No records to process.')
return true
else
log_info("Processing #{records.count} denied application(s)")
end
records.each do |record|
StemApplicantDenialMailer.build(record, nil).deliver_now
record.education_stem_automated_decision.update(denial_email_sent_at: Time.zone.now)
rescue => e
inform_on_error(record, e)
end
true
end
private
def inform_on_error(claim, error = nil)
region = EducationFacility.facility_for(region: :eastern)
StatsD.increment("worker.education_benefits_claim.applicant_denial_letter.#{region}.22-#{claim.form_type}")
exception = FormattingError.new("Could not email denial letter for #{claim.confirmation_number}.\n\n#{error}")
log_exception_to_sentry(exception)
log_exception_to_rails(exception)
end
def log_info(message)
logger.info(message)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/delete_old_applications.rb
|
# frozen_string_literal: true
module EducationForm
class DeleteOldApplications
include Sidekiq::Job
def perform
edu_claim_ids = []
saved_claim_ids = []
stem_automated_decision_ids = []
# Remove old education benefits claims and saved claims older than 2 months
EducationBenefitsClaim.eager_load(:saved_claim)
.eager_load(:education_stem_automated_decision)
.where(form_clauses)
.find_each do |record|
edu_claim_ids << record.id
saved_claim_ids << record.saved_claim&.id
stem_automated_decision_ids << record.education_stem_automated_decision&.id
end
edu_claim_ids.compact!
saved_claim_ids.compact!
stem_automated_decision_ids.compact!
delete_records_by_id(edu_claim_ids, saved_claim_ids, stem_automated_decision_ids)
end
def form_clauses
[
"(saved_claims.form_id != '22-10203' AND processed_at < '#{2.months.ago}')",
"(saved_claims.form_id = '22-10203' AND processed_at < '#{1.year.ago}')"
].join(' OR ')
end
def delete_records_by_id(edu_claim_ids, saved_claim_ids, stem_automated_decision_ids)
logger.info("Deleting #{edu_claim_ids.length} education benefits claims")
logger.info("Deleting #{saved_claim_ids.length} saved claims")
logger.info("Deleting #{stem_automated_decision_ids.length} stem automated decisions")
EducationBenefitsClaim.delete(edu_claim_ids)
SavedClaim::EducationBenefits.delete(saved_claim_ids)
EducationStemAutomatedDecision.delete(stem_automated_decision_ids)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/create_daily_year_to_date_report.rb
|
# frozen_string_literal: true
module EducationForm
class CreateDailyYearToDateReport
include Sidekiq::Job
require 'csv'
TOTALS_HASH = {
yearly: 0,
daily_submitted: 0,
daily_processed: 0
}.freeze
FORM_TYPES = EducationBenefitsClaim::FORM_TYPES.reject do |form_type|
%w[10282 10216 10215 10297 1919 0839 10275 8794 0976 0803].include?(form_type)
end.freeze
FORM_TYPE_HEADERS = EducationBenefitsClaim.form_headers(FORM_TYPES).map do |form_header|
[form_header, '', '']
end.flatten.freeze
def build_submission_relation(range_type, region, form_type, status)
range = @ranges[range_type]
relation = EducationBenefitsSubmission.where(
created_at: range,
region: region.to_s,
form_type:
)
relation = relation.where(status: 'processed') if status == :processed
relation
end
def show_individual_benefits(form_type)
%w[0993].exclude?(form_type)
end
def calculate_submissions(range_type: :year, status: :processed)
submissions = {}
application_types = EducationBenefitsClaim::APPLICATION_TYPES
FORM_TYPES.each do |form_type|
form_submissions = {}
EducationFacility::REGIONS.each do |region|
region_submissions = {}
relation = build_submission_relation(range_type, region, form_type, status)
if show_individual_benefits(form_type)
application_types.each do |application_type|
region_submissions[application_type] = relation.where(application_type => true).count
end
else
region_submissions[:all] = relation.count
end
form_submissions[region] = region_submissions
end
submissions[form_type] = form_submissions
end
submissions
end
def create_csv_header
csv_array = []
num_form_types = FORM_TYPES.size
@ranges = {}
%i[day year].each do |range_type|
@ranges[range_type] = @date.public_send("beginning_of_#{range_type}")..@date.end_of_day
end
ranges_header = [@ranges[:year].to_s, '', @ranges[:day].to_s]
submitted_header = ['', 'Submitted', 'Sent to Spool File']
csv_array << ["Submitted Vets.gov Applications - Report FYTD #{@date.year} as of #{@date}"]
csv_array << ['', '', 'DOCUMENT TYPE']
csv_array << (['RPO', 'BENEFIT TYPE'] + FORM_TYPE_HEADERS)
csv_array << (['', ''] + (ranges_header * num_form_types))
csv_array << (['', ''] + (submitted_header * num_form_types))
csv_array
end
def create_data_row(on_last_index, application_type, region, submissions, submissions_total)
row = []
FORM_TYPES.each do |form_type|
next row += ['', '', ''] if !show_individual_benefits(form_type) && !on_last_index
TOTALS_HASH.each_key do |range_type|
application_type_key = show_individual_benefits(form_type) ? application_type : :all
num_submissions = submissions[range_type][form_type][region][application_type_key]
row << num_submissions
submissions_total[form_type][range_type] += num_submissions
end
end
row
end
def create_csv_data_block(region, submissions, submissions_total)
csv_array = []
application_types = EducationBenefitsClaim::APPLICATION_TYPES
application_types.each_with_index do |application_type, i|
on_last_index = i == (application_types.size - 1)
row = [
i.zero? ? EducationFacility::RPO_NAMES[region] : '',
application_type.humanize(capitalize: false)
]
row += create_data_row(
on_last_index,
application_type,
region,
submissions,
submissions_total
)
csv_array << row
end
csv_array
end
def create_totals_row(text_rows, totals)
row = text_rows.clone
FORM_TYPES.each do |form_type|
TOTALS_HASH.each_key do |range_type|
row << totals[form_type][range_type]
end
end
row
end
def get_totals_hash_with_form_types
totals = {}
FORM_TYPES.each do |form_type|
totals[form_type] = TOTALS_HASH.dup
end
totals
end
def convert_submissions_to_csv_array
submissions_csv_array = []
submissions = {
yearly: calculate_submissions,
daily_submitted: calculate_submissions(range_type: :day, status: :submitted),
daily_processed: calculate_submissions(range_type: :day, status: :processed)
}
grand_totals = get_totals_hash_with_form_types
EducationFacility::REGIONS.each do |region|
submissions_total = get_totals_hash_with_form_types
submissions_csv_array += create_csv_data_block(region, submissions, submissions_total)
submissions_csv_array << create_totals_row(['', 'TOTAL'], submissions_total)
submissions_total.each do |form_type, form_submissions|
form_submissions.each do |range_type, total|
grand_totals[form_type][range_type] += total
end
end
end
submissions_csv_array << create_totals_row(['ALL RPOS TOTAL', ''], grand_totals)
submissions_csv_array
end
def create_csv_array
csv_array = []
csv_array += create_csv_header
csv_array += convert_submissions_to_csv_array
csv_array << (['', ''] + FORM_TYPE_HEADERS)
csv_array
end
def perform
# use yesterday as the date otherwise we will miss applications that are submitted after the report is run
@date = Time.zone.today - 1.day
folder = 'tmp/daily_reports'
FileUtils.mkdir_p(folder)
filename = "#{folder}/#{@date}.csv"
CSV.open(filename, 'wb') do |csv|
create_csv_array.each do |row|
csv << row
end
end
return unless FeatureFlipper.send_edu_report_email?
YearToDateReportMailer.build(filename).deliver_now
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/education_facility.rb
|
# frozen_string_literal: true
module EducationForm
class EducationFacility
# sourced from http://www.vba.va.gov/pubs/forms/VBA-22-1990-ARE.pdf
EASTERN = %w[
CO CT DE DC IA IL IN KS KY MA ME MI MD MN MO MT NC ND NE
NH NJ NY OH PA RI SD TN VT VA WV WI WY VI AA
].freeze
# We need to keep SOUTHERN and CENTRAL because existing records will have
# this as a region, and we need to continue to show the counts
# in the YTD reports.
SOUTHERN = %w[].freeze
CENTRAL = %w[].freeze
WESTERN = %w[
AK AL AR AZ CA FL GA HI ID LA MS NM NV OK OR SC TX UT WA
GU PR AP
].freeze
ADDRESSES = {
eastern: [
'P.O. Box 4616',
'Buffalo, NY 14240-4616'
],
southern: [
'P.O. Box 100022',
'Decatur, GA 30031-7022'
],
central: [
'9770 Page Avenue',
'Suite 101 Education',
'St. Louis, MO 63132-1502'
],
western: [
'P.O. Box 8888',
'Muskogee, OK 74402-8888'
]
}.freeze
REGIONS = ADDRESSES.keys
RPO_NAMES = {
eastern: 'BUFFALO (307)',
southern: 'ATLANTA (316)',
central: 'ST. LOUIS (331)',
western: 'MUSKOGEE (351)'
}.freeze
EMAIL_NAMES = {
eastern: 'Eastern Region',
southern: 'Southern Region',
central: 'Central Region',
western: 'Western Region'
}.freeze
FACILITY_IDS = {
eastern: 307,
southern: 316,
central: 331,
western: 351
}.freeze
def self.facility_for(region:)
FACILITY_IDS[region]
end
def self.rpo_name(region:)
RPO_NAMES[region]
end
def self.region_for(model)
record = model.open_struct_form
address = routing_address(record, form_type: model.form_type)
# special case 0993
return :western if %w[0993].include?(model.form_type)
# special case 0994
# special case 10203
return :eastern if %w[0994 10203 10297].include?(model.form_type)
# special case Philippines
return :western if address&.country == 'PHL'
check_area(address)
end
def self.check_area(address)
area = address&.state
if WESTERN.any? { |state| state == area }
:western
else
:eastern
end
end
def self.education_program(record)
record.educationProgram || record.school
end
# Claims are sent to different RPOs based first on the location of the school
# that the claim is relating to (either `school` or `newSchool` in our submissions)
# or to the applicant's address (either as a relative or the veteran themselves)
def self.routing_address(record, form_type:)
case form_type.upcase
when '1990'
education_program(record)&.address || record.veteranAddress
when '5490', '5495'
record.educationProgram&.address || record.relativeAddress
when '1995'
record.newSchool&.address || record.veteranAddress
end
end
def self.regional_office_for(model)
region = region_for(model)
['VA Regional Office', ADDRESSES[region]].join("\n")
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq
|
code_files/vets-api-private/app/sidekiq/education_form/create_spool_submissions_report.rb
|
# frozen_string_literal: true
module EducationForm
class CreateSpoolSubmissionsReport
require 'csv'
include Sidekiq::Job
def format_name(full_name)
return if full_name.blank?
[full_name['first'], full_name['last']].compact.join(' ')
end
def processed_at_range
(@time - 24.hours)..@time
end
def create_csv_array
data = {
csv_array: [],
stem_exists: false
}
data[:csv_array] << ['Claimant Name', 'Veteran Name', 'Confirmation #', 'Time Submitted', 'RPO']
EducationBenefitsClaim.where(
processed_at: processed_at_range
).find_each do |education_benefits_claim|
parsed_form = education_benefits_claim.parsed_form
data[:csv_array] << [
format_name(parsed_form['relativeFullName']),
format_name(parsed_form['veteranFullName']),
education_benefits_claim.confirmation_number,
education_benefits_claim.processed_at.to_s,
education_benefits_claim.regional_processing_office
]
end
data
end
def perform
@time = Time.zone.now
folder = 'tmp/spool_reports'
FileUtils.mkdir_p(folder)
filename = "#{folder}/#{@time.to_date}.csv"
csv_array_data = create_csv_array
csv_array = csv_array_data[:csv_array]
CSV.open(filename, 'wb') do |csv|
csv_array.each do |row|
csv << row
end
end
return unless FeatureFlipper.send_edu_report_email?
SpoolSubmissionsReportMailer.build(filename).deliver_now
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/base.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class Base
include ActionView::Helpers::TextHelper # Needed for word_wrap
require 'erb'
TEMPLATE_PATH = Rails.root.join('app', 'sidekiq', 'education_form', 'templates')
attr_accessor :form, :record, :text
def self.build(app)
klass = "EducationForm::Forms::VA#{app.form_type}".constantize
klass.new(app)
end
def direct_deposit_type(type)
dd_types = { 'STARTUPDATE' => 'Start or Update', 'STOP' => 'Stop', 'NOCHANGE' => 'Do Not Change' }
dd_types[type&.upcase]
end
def ssn_gender_dob(veteran = true)
prefix = veteran ? 'veteran' : 'relative'
ssn = @applicant.public_send("#{prefix}SocialSecurityNumber")
gender = @applicant.gender
dob = @applicant.public_send("#{prefix}DateOfBirth")
"SSN: #{ssn} Sex: #{gender} Date of Birth: #{dob}"
end
def benefit_type(application)
application.benefit&.gsub('chapter', 'CH')
end
def disclosure_for(type)
return if type.blank?
"#{parse_with_template_path("1990-disclosure/_#{type}")}\n"
end
def header_form_type
"V#{@record.form_type}"
end
delegate :school, to: :@applicant
def applicant_name
@applicant.veteranFullName
end
def applicant_ssn
@applicant.veteranSocialSecurityNumber
end
def initialize(app)
@record = app
@form = app.open_struct_form
@text = format unless instance_of?(Base)
end
# @note
# The input fixtures in {spec/fixtures/education_benefits_claims/**/*.json contain
# Windows-1252 encoding "double right-single-quotation-mark", (’) Unicode %u2019
# but .spl file (expected output) contains ASCII apostrophe ('), code %27.
#
# Workaround is to sub the ASCII apostrophe, though other non-UTF-8 chars might break specs
#
# Convert the JSON/OStruct document into the text format that we submit to the backend
def format
@applicant = @form
# the spool file has a requirement that lines be 80 bytes (not characters), and since they
# use windows-style newlines, that leaves us with a width of 78
wrapped = word_wrap(parse_with_template_path(@record.form_type), line_width: 78)
wrapped = wrapped.gsub(/’|‘/, "'").gsub(/”|“/, '"')
# We can only send ASCII, so make a best-effort at that.
transliterated = ActiveSupport::Inflector.transliterate(wrapped, locale: :en)
# Trim any lines that end in whitespace, but keep the lines themselves
transliterated.gsub!(/ +\n/, "\n")
# The spool file must actually use windows style linebreaks
transliterated.gsub("\n", EducationForm::CreateDailySpoolFiles::WINDOWS_NOTEPAD_LINEBREAK)
end
def parse_with_template(template)
# Because our template files end in newlines, we have to
# chomp off the final rendered line to get the correct
# output. Any intentionally blank lines before the final
# one will remain.
ERB.new(template, trim_mode: '-').result(binding).chomp
end
def parse_with_template_path(path)
parse_with_template(get_template(path))
end
def header
parse_with_template_path('header')
end
def get_template(filename)
File.read(File.join(TEMPLATE_PATH, "#{filename}.erb"))
end
### Common ERB Helpers
# N/A is used for "the user wasn't shown this option", which is distinct from Y/N.
def yesno(bool)
return 'N/A' if bool.nil?
bool ? 'YES' : 'NO'
end
def yesno_or_blank(bool)
return '' if bool.nil?
bool ? 'YES' : 'NO'
end
def value_or_na(value)
value.nil? ? 'N/A' : value
end
# is this needed? will it the data come in the correct format? better to have the helper..
def to_date(date)
date || (' ' * 10) # '00/00/0000'.length
end
def full_name(name)
return '' if name.nil?
[name.first, name.middle, name.last, name&.suffix].compact.join(' ')
end
def school_name
school&.name&.upcase&.strip
end
def school_name_and_addr(school)
return '' if school.nil?
[
school.name,
full_address(school.address)
].compact.join("\n")
end
def full_address(address, indent: false)
return '' if address.nil?
seperator = indent ? "\n " : "\n"
[
address.street,
address.street2,
[address.city, address.state, address.postalCode].compact.join(', '),
address.country
].compact.join(seperator).upcase
end
def full_address_with_street3(address, indent: false)
return '' if address.nil?
seperator = indent ? "\n " : "\n"
[
address.street,
address.street2,
address.street3,
[address.city, address.state, address.postalCode].compact.join(', '),
address.country
].compact.join(seperator).upcase
end
def hours_and_type(training)
return_val = training&.hours&.to_s
return '' if return_val.blank?
hours_type = training&.hoursType
return_val += " (#{hours_type})" if hours_type.present?
return_val
end
def employment_history(job_history, post_military: nil)
wrapped_list = Array(job_history)
wrapped_list = wrapped_list.select { |job| job.postMilitaryJob == post_military } unless post_military.nil?
# we need at least one record to be in the form.
wrapped_list << OpenStruct.new if wrapped_list.empty?
wrapped_list.map do |job|
" Principal Occupation: #{job.name}
Number of Months: #{job.months}
License or Rating: #{job.licenseOrRating}"
end.join("\n\n")
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_0839.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA0839 < Base
def initialize(education_benefits_claim)
@education_benefits_claim = education_benefits_claim
@applicant = education_benefits_claim.parsed_form
super(app)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_5490.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA5490 < Base
# rubocop:disable Layout/LineLength
PREVIOUS_BENEFITS = {
'disability' => 'DISABILITY COMPENSATION OR PENSION',
'dic' => "DEPENDENTS' INDEMNITY COMPENSATION",
'chapter31' => 'VOCATIONAL REHABILITATION BENEFITS (Chapter 31)',
'chapter35' => "VETERANS EDUCATION ASSISTANCE BASED ON SOMEONE ELSE'S SERVICE: CHAPTER 35 - SURVIVORS' AND DEPENDENTS' EDUCATIONAL ASSISTANCE PROGRAM (DEA)",
'chapter33' => "VETERANS EDUCATION ASSISTANCE BASED ON SOMEONE ELSE'S SERVICE: CHAPTER 33 - POST-9/11 GI BILL MARINE GUNNERY SERGEANT DAVID FRY SCHOLARSHIP",
'transferOfEntitlement' => "VETERANS EDUCATION ASSISTANCE BASED ON SOMEONE ELSE'S SERVICE: TRANSFERRED ENTITLEMENT"
}.freeze
# rubocop:enable Layout/LineLength
HIGH_SCHOOL_STATUS = {
'graduated' => 'Graduated from high school',
'discontinued' => 'Discontinued high school',
'graduationExpected' => 'Expect to graduate from high school',
'ged' => 'Awarded GED',
'neverAttended' => 'Never attended high school'
}.freeze
def applicant_name
@applicant.relativeFullName
end
def applicant_ssn
@applicant.relativeSocialSecurityNumber
end
def school
@applicant.educationProgram
end
def high_school_status
status = @applicant.highSchool&.status
return if status.nil?
HIGH_SCHOOL_STATUS[status]
end
def previously_applied_for_benefits?
previous_benefits.present?
end
def previous_benefits
previous_benefits = @form.previousBenefits
return if previous_benefits.blank?
previous_benefits_arr = previous_benefits.to_h.map do |key, value|
PREVIOUS_BENEFITS[key.to_s] if value == true
end.compact
if previous_benefits.ownServiceBenefits.present?
own_service_benefits_txt = 'VETERANS EDUCATION ASSISTANCE BASED ON YOUR OWN SERVICE SPECIFY BENEFIT(S): '
own_service_benefits_txt += previous_benefits.ownServiceBenefits
previous_benefits_arr << own_service_benefits_txt
end
if previous_benefits.other.present?
previous_benefits_arr << "OTHER; Specify benefit(s): #{previous_benefits.other}"
end
previous_benefits_arr.join("\n")
end
def veteran_date_of_death_label
return 'Date of death or MIA/POW:' if @applicant.benefit != 'chapter33' || @applicant.sponsorStatus.nil?
case @applicant.sponsorStatus
when 'diedOnDuty'
label = 'Died while serving on active duty or duty other than active duty:'
when 'diedFromDisabilityOrOnReserve'
label = 'Died from a service-connected disability while a member of the Selected Reserve:'
when 'powOrMia'
label = 'Listed as MIA or POW:'
end
label
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_1990.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA1990 < Base
### ERB HELPERS
CH33_TYPES = {
'chapter1607' => 'CH33_1607', 'chapter1606' => 'CH33_1606', 'chapter30' => 'CH33_30'
}.freeze
# If multiple benefit types are selected, we've been told to just include whichever
# one is 'first' in the header.
def benefit_type(application)
return 'CH1606' if application.chapter1606
return 'CH1607' if application.chapter1607
return 'CH33' if application.chapter33
return 'CH30' if application.chapter30
'CH32' if application.chapter32
end
def non_va_assistance
@applicant.currentlyActiveDuty&.nonVaAssistance
end
def school
@applicant.educationProgram
end
def education_type
@applicant.educationProgram&.educationType
end
# Some descriptive text that's included near the top of the 22-1990 form. Because they can make
# multiple selections, we have to add all the selected ones.
def disclosures(application)
disclosure_texts = []
disclosure_texts << disclosure_for('CH30') if application.chapter30
disclosure_texts << disclosure_for('CH1606') if application.chapter1606
disclosure_texts << disclosure_for('CH32') if application.chapter32
if application.chapter33
ch33_type = CH33_TYPES.fetch(application.benefitsRelinquished, 'CH33')
disclosure_texts << disclosure_for(ch33_type)
end
disclosure_texts.join("\n#{'*' * 78}\n\n")
end
def rotc_scholarship_amounts(scholarships)
# there are 5 years, all of which can be blank.
# Wrap the array to a size of 5 to meet this requirement
wrapped_list = Array(scholarships)
Array.new(5) do |idx|
" Year #{idx + 1}: Amount: #{wrapped_list[idx]&.amount}\n"
end.join("\n")
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_5495.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA5495 < Base
def school
@applicant.educationProgram
end
def applicant_name
@applicant.relativeFullName
end
def applicant_ssn
@applicant.relativeSocialSecurityNumber
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_1995.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA1995 < Base
FORM_TYPES = {
chapter30: 'CH30',
chapter32: 'CH32',
chapter33: 'CH33',
chapter33Post911: 'CH33',
chapter33FryScholarship: 'CH33',
chapter35: 'CH35',
chapter1606: 'CH1606',
chapter1607: 'CH1607',
transferOfEntitlement: 'TransferOfEntitlement'
}.freeze
def school
@applicant.newSchool
end
def header_abbreviated_form_type(header_form_type)
return 'CH33' if header_form_type.eql?('transferOfEntitlement')
FORM_TYPES[header_form_type&.to_sym]
end
def form_type
FORM_TYPES[@applicant.benefit&.to_sym]
end
def form_benefit
@applicant.benefitUpdate&.titleize
end
def header_form_type
@applicant.rudisillReview == 'Yes' ? '1995R' : 'V1995'
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_8794.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA8794 < Base
def initialize(education_benefits_claim)
@education_benefits_claim = education_benefits_claim
@applicant = education_benefits_claim.parsed_form
super(education_benefits_claim)
end
def designating_official_name
@applicant['designatingOfficial']['fullName']
end
def designating_official_title
@applicant['designatingOfficial']['title']
end
def designating_official_email
@applicant['designatingOfficial']['emailAddress']
end
def institution_name
@applicant['institutionDetails']['institutionName']
end
def facility_code
@applicant['institutionDetails']['facilityCode']
end
def va_facility_code?
@applicant['institutionDetails']['hasVaFacilityCode']
end
def primary_official_name
@applicant['primaryOfficialDetails']['fullName']
end
def primary_official_title
@applicant['primaryOfficialDetails']['title']
end
def primary_official_email
@applicant['primaryOfficialDetails']['emailAddress']
end
def training_completion_date
@applicant['primaryOfficialTraining']['trainingCompletionDate']
end
def training_exempt
@applicant['primaryOfficialTraining']['trainingExempt']
end
def va_education_benefits?
@applicant['primaryOfficialBenefitStatus']['hasVaEducationBenefits']
end
def additional_certifying_officials
@applicant['additionalCertifyingOfficials'] || []
end
def read_only_certifying_official?
@applicant['hasReadOnlyCertifyingOfficial']
end
def read_only_certifying_officials
@applicant['readOnlyCertifyingOfficial'] || []
end
def remarks
@applicant['remarks']
end
def statement_of_truth_signature
@applicant['statementOfTruthSignature']
end
def date_signed
@applicant['dateSigned']
end
def header_form_type
'V8794'
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_10216.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA10216 < Base
def initialize(education_benefits_claim)
@education_benefits_claim = education_benefits_claim
@applicant = education_benefits_claim.parsed_form
super(app)
end
def institution_name
@applicant['institutionDetails']['institutionName']
end
def facility_code
@applicant['institutionDetails']['facilityCode']
end
def term_start_date
@applicant['institutionDetails']['termStartDate']
end
def beneficiary_students
@applicant['studentRatioCalcChapter']['beneficiaryStudent']
end
def total_students
@applicant['studentRatioCalcChapter']['numOfStudent']
end
def va_beneficiary_percentage
@applicant['studentRatioCalcChapter']['VaBeneficiaryStudentsPercentage']
end
def calculation_date
@applicant['studentRatioCalcChapter']['dateOfCalculation']
end
def header_form_type
'V10216'
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_0803.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA0803 < Base
def initialize(education_benefits_claim)
@education_benefits_claim = education_benefits_claim
@applicant = education_benefits_claim.parsed_form
super(app)
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_0994.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA0994 < Base
def header_form_type
'V0994'
end
def benefit_type
'VetTec'
end
HIGH_TECH_AREA_NAMES = {
computerProgramming: 'Computer programming',
dataProcessing: 'Data processing',
computerSoftware: 'Computer software',
informationSciences: 'Information sciences',
mediaApplication: 'Media application'
}.freeze
SALARY_TEXT = {
lessThanTwenty: '<$20,000',
twentyToThirtyFive: '$20,000-$35,000',
thirtyFiveToFifty: '$35,000-$50,000',
fiftyToSeventyFive: '$50,000-$75,000',
moreThanSeventyFive: '>$75,000'
}.freeze
EDUCATION_TEXT = {
some_high_school: 'Some High School',
high_school_diploma_or_GED: 'High school diploma or GED',
some_college: 'Some college',
associates_degree: 'Associate’s degree',
bachelors_degree: 'Bachelor’s degree',
masters_degree: 'Master’s degree',
doctoral_degree: 'Doctoral degree',
other: 'Other'
}.freeze
COURSE_TYPE_TEXT = {
inPerson: 'In Person',
online: 'Online',
both: 'Both'
}.freeze
def applicant_name
@applicant.applicantFullName
end
def applicant_ssn
@applicant.applicantSocialSecurityNumber
end
def new_bank_info?
@applicant.bankAccount&.routingNumber.present? ||
@applicant.bankAccount&.accountNumber.present? ||
@applicant.bankAccount&.accountType.present?
end
def bank_routing_number
if @applicant.bankAccount&.routingNumber.present?
@applicant.bankAccount.routingNumber
elsif !new_bank_info?
@applicant.prefillBankAccount&.bankRoutingNumber
end
end
def bank_account_number
if @applicant.bankAccount&.accountNumber.present?
@applicant.bankAccount.accountNumber
elsif !new_bank_info?
@applicant.prefillBankAccount&.bankAccountNumber
end
end
def bank_account_type
if @applicant.bankAccount&.accountType.present?
@applicant.bankAccount.accountType
elsif !new_bank_info?
@applicant.prefillBankAccount&.bankAccountType
end
end
def location
return '' if @applicant.vetTecProgramLocations.blank?
"#{@applicant.vetTecProgramLocations.city}, #{@applicant.vetTecProgramLocations.state}"
end
def high_tech_area_names
return 'N/A' unless @applicant.currentHighTechnologyEmployment
return '' if @applicant.highTechnologyEmploymentTypes.blank?
areas = []
@applicant.highTechnologyEmploymentTypes.each do |area|
areas.push(HIGH_TECH_AREA_NAMES[area.to_sym])
end
areas.join("\n")
end
def education_level_name
return '' if @applicant.highestLevelofEducation.blank?
return @applicant.otherEducation if @applicant.highestLevelofEducation == 'other'
EDUCATION_TEXT[@applicant.highestLevelofEducation.to_sym]
end
def course_type_name(course_type)
return '' if course_type.blank?
COURSE_TYPE_TEXT[course_type.to_sym]
end
def salary_text
return 'N/A' unless @applicant.currentHighTechnologyEmployment
return '' if @applicant.currentSalary.blank?
SALARY_TEXT[@applicant.currentSalary.to_sym]
end
def get_program_block(program)
city = program.courseType == 'online' && program.location&.city.blank? ? 'N/A' : program.location&.city
state = program.courseType == 'online' && program.location&.state.blank? ? 'N/A' : program.location&.state
[
["\n Provider name: ", program.providerName].join,
["\n Program name: ", program.programName].join,
["\n Course type: ", course_type_name(program.courseType)].join,
"\n Location:",
["\n City: ", city].join,
["\n State: ", state].join,
["\n Planned start date: ", program.plannedStartDate].join
].join
end
def program_text
return '' if @applicant.vetTecPrograms.blank? && @applicant.hasSelectedPrograms
return 'N/A' if @applicant.hasSelectedPrograms.blank?
program_blocks = []
@applicant.vetTecPrograms.each do |program|
program_blocks.push(get_program_block(program))
end
program_blocks.join("\n")
end
def full_address_with_street3(address, indent: false)
return '' if address.nil?
seperator = indent ? "\n " : "\n"
[
address.street,
address.street2,
address.street3,
[address.city, address.state, address.postalCode].compact.join(', '),
address.country
].compact.join(seperator).upcase
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_0976.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA0976 < Base
def initialize(education_benefits_claim)
@education_benefits_claim = education_benefits_claim
@applicant = education_benefits_claim.parsed_form
super(education_benefits_claim)
end
def header_form_type
'V0976'
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_1919.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA1919 < Base
def initialize(education_benefits_claim)
@education_benefits_claim = education_benefits_claim
@applicant = education_benefits_claim.parsed_form
super(education_benefits_claim)
end
def institution_name
@applicant['institutionDetails']['institutionName']
end
def facility_code
@applicant['institutionDetails']['facilityCode']
end
def certifying_official_name
official = @applicant['certifyingOfficial']
return '' unless official
"#{official['first']} #{official['last']}"
end
def certifying_official_role
role = @applicant['certifyingOfficial']['role']
return '' unless role
role['level'] == 'other' ? role['other'] : role['level']
end
def proprietary_conflicts_count
conflicts = @applicant['proprietaryProfitConflicts']
return 0 unless conflicts
[conflicts.length, 2].min # Max 2 as per requirement
end
def proprietary_conflicts
conflicts = @applicant['proprietaryProfitConflicts']
return [] unless conflicts
conflicts.first(2) # Take only first 2
end
def all_proprietary_conflicts_count
conflicts = @applicant['allProprietaryProfitConflicts']
return 0 unless conflicts
[conflicts.length, 2].min # Max 2 as per requirement
end
def all_proprietary_conflicts
conflicts = @applicant['allProprietaryProfitConflicts']
return [] unless conflicts
conflicts.first(2) # Take only first 2
end
def header_form_type
'V1919'
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_10203.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA10203 < Base
def initialize(app)
@stem_automated_decision = app.education_stem_automated_decision
super(app)
end
def denied?
@stem_automated_decision&.automated_decision_state == 'denied'
end
def header_form_type
denied? ? '10203DNY' : 'V10203'
end
def form_identifier
denied? ? 'VA Form 22-10203DNY' : 'VA Form 22-10203'
end
def form_benefit
@applicant.benefit&.titleize
end
def school_name
@applicant.schoolName.upcase.strip
end
def any_remaining_benefit
yesno(%w[moreThanSixMonths sixMonthsOrLess].include?(benefit_left))
end
def receive_text_message
return false if @applicant.receiveTexts.nil?
@applicant.receiveTexts
end
def benefit_left
@benefit_left ||= @applicant.benefitLeft
end
def pursuing_teaching_cert
@pursuing_teaching_cert ||= @applicant.isPursuingTeachingCert
end
def enrolled_stem
@enrolled_stem ||= @applicant.isEnrolledStem
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_10282.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA10282 < Base
SALARY_TYPES = {
moreThanSeventyFive: 'More than $75,000',
thirtyFiveToFifty: '$35,000 - $50,000',
fiftyToSeventyFive: '$50,000 - $75,000',
twentyToThirtyFive: '$20,000 - $35,000',
lessThanTwenty: 'Less than $20,000'
}.freeze
TECH_AREAS = {
CP: 'Computer Programming',
DP: 'Data Processing',
CS: 'Cyber Security',
IS: 'Information Security',
MA: 'Mobile Applications',
NA: 'Not Applicable'
}.freeze
GENDER_TYPES = {
'M' => 'Male',
'W' => 'Female',
'TW' => 'Transgender Woman',
'TM' => 'Transgender Man',
'NB' => 'Non-Binary',
'0' => 'Other',
'NA' => 'Prefer Not to Answer'
}.freeze
EDUCATION_LEVELS = {
'HS' => 'High School',
'AD' => 'Associate Degree',
'BD' => "Bachelor's Degree",
'MD' => "Master's Degree",
'DD' => 'Doctorate Degree',
'NA' => 'Prefer Not to Answer'
}.freeze
MILITARY_TYPES = {
'veteran' => 'Veteran',
'veteransSpouse' => "Veteran's Spouse",
'veteransChild' => "Veteran's Child",
'veteransCaregiver' => "Veteran's Caregiver",
'activeduty' => 'Active Duty',
'nationalGuard' => 'National Guard',
'reservist' => 'Reservist',
'individualReadyReserve' => 'Individual Ready Reserve'
}.freeze
ETHNICITY_TYPES = {
'HL' => 'Hispanic or Latino',
'NHL' => 'Not Hispanic or Latino',
'NA' => 'Prefer Not to Answer'
}.freeze
# rubocop:disable Lint/MissingSuper
def initialize(education_benefits_claim)
@education_benefits_claim = education_benefits_claim
@applicant = education_benefits_claim.parsed_form
end
# rubocop:enable Lint/MissingSuper
def name
"#{first_name} #{last_name}"
end
def first_name
@applicant['veteranFullName']['first']
end
def last_name
@applicant['veteranFullName']['last']
end
def military_affiliation
MILITARY_TYPES[@applicant['veteranDesc']] || 'Not specified'
end
def phone_number
@applicant.dig('contactInfo', 'mobilePhone') ||
@applicant.dig('contactInfo', 'homePhone') ||
'Not provided'
end
def email_address
@applicant['contactInfo']['email']
end
def country
@applicant['country']
end
def state
@applicant['state']
end
def race_ethnicity
races = []
origin_race = @applicant['originRace']
races << 'American Indian or Alaska Native' if origin_race['isAmericanIndianOrAlaskanNative']
races << 'Asian' if origin_race['isAsian']
races << 'Black or African American' if origin_race['isBlackOrAfricanAmerican']
races << 'Native Hawaiian or Other Pacific Islander' if origin_race['isNativeHawaiianOrOtherPacificIslander']
races << 'White' if origin_race['isWhite']
races << 'Prefer Not to Answer' if origin_race['noAnswer']
return 'Not specified' if races.empty?
races.join(', ')
end
def gender
GENDER_TYPES[@applicant['gender']] || 'Not specified'
end
def education_level
EDUCATION_LEVELS[@applicant['highestLevelOfEducation']['level']] || 'Not specified'
end
def employment_status
@applicant['currentlyEmployed'] ? 'Yes' : 'No'
end
def salary
SALARY_TYPES[@applicant['currentAnnualSalary']&.to_sym] || 'Not specified'
end
def technology_industry
return 'No' unless @applicant['isWorkingInTechIndustry']
TECH_AREAS[@applicant['techIndustryFocusArea']&.to_sym] || 'Not specified'
end
def header_form_type
'V10282'
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_10275.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA10275 < Base
def initialize(education_benefits_claim)
@education_benefits_claim = education_benefits_claim
@applicant = education_benefits_claim.parsed_form
super(app)
end
def header_form_type
'V10275'
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_0993.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA0993 < Base
def header_form_type
'OPTOUT'
end
def applicant_name
@applicant.claimantFullName
end
def applicant_ssn
@applicant.claimantSocialSecurityNumber
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_10297.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA10297 < Base
def header_form_type
'V10297'
end
def benefit_type
'VetTec'
end
HIGH_TECH_AREA_NAMES = {
computerProgramming: 'Computer programming',
computerSoftware: 'Computer software',
mediaApplication: 'Media application',
dataProcessing: 'Data processing',
informationSciences: 'Information sciences',
somethingElse: 'Other'
}.freeze
SALARY_TEXT = {
lessThanTwenty: '<$20,000',
twentyToThirtyFive: '$20,000-$35,000',
thirtyFiveToFifty: '$35,000-$50,000',
fiftyToSeventyFive: '$50,000-$75,000',
moreThanSeventyFive: '>$75,000'
}.freeze
EDUCATION_TEXT = {
HS: 'High school',
AD: 'Associate’s degree',
BD: 'Bachelor’s degree',
MD: 'Master’s degree',
DD: 'Doctoral degree',
NA: 'Other'
}.freeze
COURSE_TYPE_TEXT = {
inPerson: 'In Person',
online: 'Online',
both: 'Both'
}.freeze
def applicant_name
@applicant.applicantFullName
end
def applicant_ssn
@applicant.ssn
end
def applicant_va_file_number
@applicant.vaFileNumber
end
def bank_routing_number
@applicant.bankAccount&.routingNumber
end
def bank_account_number
@applicant.bankAccount&.accountNumber
end
def bank_account_type
@applicant.bankAccount&.accountType
end
def education_level_name
return '' if @applicant.highestLevelOfEducation.blank?
EDUCATION_TEXT[@applicant.highestLevelOfEducation.to_sym]
end
def high_tech_area_name
return '' if @applicant.technologyAreaOfFocus.blank?
HIGH_TECH_AREA_NAMES[@applicant.technologyAreaOfFocus.to_sym]
end
def salary_text
return 'N/A' unless @applicant.isEmployed && @applicant.isInTechnologyIndustry
return '' if @applicant.currentSalary.blank?
SALARY_TEXT[@applicant.currentSalary.to_sym]
end
def get_program_block(program)
program.providerAddress
[
["\n Provider name: ", program.providerName].join,
"\n Location:",
["\n City: ", program.providerAddress.city].join,
["\n State: ", program.providerAddress.state].join
].join
end
def program_text
return '' if @applicant.trainingProviders&.providers.blank?
program_blocks = []
@applicant.trainingProviders.providers.each do |program|
program_blocks.push(get_program_block(program))
end
program_blocks.push(["\n Planned start date: ", @applicant.trainingProviders.plannedStartDate].join)
program_blocks.join("\n")
end
def full_address_with_street2(address, indent: false)
return '' if address.nil?
seperator = indent ? "\n " : "\n"
[
address.street,
address.street2,
[address.city, address.state, address.postalCode].compact.join(', '),
address.country
].compact.join(seperator).upcase
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/forms/va_10215.rb
|
# frozen_string_literal: true
module EducationForm::Forms
class VA10215 < Base
def initialize(education_benefits_claim)
@education_benefits_claim = education_benefits_claim
@applicant = education_benefits_claim.parsed_form
super(app)
end
def institution_name
@applicant['institutionDetails']['institutionName']
end
def facility_code
@applicant['institutionDetails']['facilityCode']
end
def term_start_date
@applicant['institutionDetails']['termStartDate']
end
def calculation_date
@applicant['institutionDetails']['dateOfCalculations']
end
def programs
@applicant['programs']
end
def header_form_type
'V10215'
end
end
end
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/post_high_school_trainings.erb
|
Education After High School
---------------------------
<% Array(@applicant.postHighSchoolTrainings).each do |training| %>
Name and Location of College or Training Provider:
<%= training&.name %>
<%= training.city %>, <%= training.state %>
Date of Training: From: <%= to_date(training&.dateRange&.from) %> To: <%= to_date(training&.dateRange&.to) %>
Hours: <%= hours_and_type(training) %>
Degree/Diploma/Certificate: <%= training&.degreeReceived %>
Major Field/Course of Study: <%= training&.major %>
<% end %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/footer.erb
|
Electronically Received by VA: <%= to_date(@record.created_at.strftime("%Y-%m-%d")) %>
Confirmation #: <%= @applicant.confirmation_number %>
*END*
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/10203.erb
|
<%= header %>
CH33
*START*
<%= form_identifier %>
OMB Control #: 2900-0878
APPLICATION FOR EDITH NOURSE ROGERS STEM SCHOLARSHIP
----------------------------------------------------
APPLICANT INFORMATION
---------------------
SSN: <%= value_or_na(@applicant.veteranSocialSecurityNumber) %> VA File Number: N/A
Name: <%= full_name(@applicant.veteranFullName) %>
Address:
<%= full_address(@applicant.veteranAddress) %>
Telephone Numbers: Home: <%= @applicant.homePhone %>
Mobile: <%= @applicant.mobilePhone %>
Email Address: <%= @applicant.email %>
Preferred Method of Contact: <%= @applicant.preferredContactMethod %>
I would like to receive text message from VA about my GI Bill benefits: <%= yesno(receive_text_message) %>
Direct Deposit:
Type of Account: <%= @applicant.bankAccount&.accountType %>
Routing/Transit #: <%= @applicant.bankAccount&.routingNumber %> Account #: <%= @applicant.bankAccount&.accountNumber %>
Are you currently on active duty or do you anticipate you will
be going on active duty?: <%= yesno(@applicant.isActiveDuty) %>
Do you currently have remaining entitlement under any VA Education Benefits?:
<%= any_remaining_benefit %>
Benefit: <%= form_benefit %>
APPLICANT’S COURSE OF STUDY, CERTIFICATION AND SIGNATURE
--------------------------------------------------------
Type of Education Program that you are currently enrolled in:
<% if @applicant.isEnrolledStem -%>
- Education program that leads to an 'Undergraduate Degree' in a
standard, undergraduate college degree
<% end -%>
<% if @applicant.isPursuingTeachingCert -%>
- Earned a degree from an Education Program listed under 'Approved Stem
Programs' and I am now enrolled in a program leading to a 'Teaching
Certification'
<% end -%>
<% if @applicant.isPursuingClinicalTraining -%>
- Do you have a STEM bachelor's or graduate degree and
are now pursuing a covered clinical training program for
health care professionals? <%= yesno(@applicant.isPursuingClinicalTraining) %>
<% end -%>
Program Name: <%= @applicant.degreeName %>
Provide the location where you plan to or will start training:
<%= @applicant.schoolName %>
<%= @applicant.schoolCity %>, <%= @applicant.schoolState %>
<%= @applicant.schoolCountry %>
Auto Email Sent to SCO: <%= yesno(@applicant.scoEmailSent) %>
<% if @stem_automated_decision.present? -%>
Applicant has POA: <%= yesno(@stem_automated_decision.poa) %>
<% end -%>
Applicant School Email Address: <%= @applicant.schoolEmailAddress %>
Applicant School ID: <%= @applicant.schoolStudentId %>
<% if @applicant.isActiveDuty -%>
As an active-duty service member, you have consulted with an Education Service
Officer (ESO) regarding your education program.
<% else -%>
Certification and Signature of Applicant
Signature of Applicant Date
<% end -%>
<%= parse_with_template_path('footer') %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/header.erb
|
*INIT*
<%= applicant_name&.first&.upcase&.strip %>
<%= applicant_name&.middle&.upcase&.strip %>
<%= applicant_name&.last&.upcase&.strip %>
<% if %w[VE1990 V0994 V10297 OPTOUT].include?(header_form_type) -%>
<%= applicant_ssn&.gsub(/[^\d]/, '') %>
<% else -%>
<%= @applicant.veteranSocialSecurityNumber&.gsub(/[^\d]/, '') %>
<% end -%>
<%= applicant_ssn&.gsub(/[^\d]/, '') %>
<%= header_form_type %>
<%= school_name %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/non_va_assistance.erb
|
For Active Duty Claimants Only. Are you receiving or do you anticipate receiving any money (including but not limited to Federal Tuition Assistance) from the Armed Forces or Public Health Service for the course for which you have applied to the VA for Education Benefits? If you receive such benefits during any part of your training, check 'Yes.' Note: If you are only applying for Tuition Assistance Top-Up, check 'No' to this item. <%= yesno(non_va_assistance) %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/1995.erb
|
<%= parse_with_template_path('header_1995') %>
<% if @applicant.benefitAppliedFor -%>
<%= header_abbreviated_form_type(@applicant.benefitAppliedFor)%>
<% else -%>
<%= header_abbreviated_form_type(@applicant.benefitUpdate)%>
<% end -%>
*START*
VA Form 22-1995
OMB Control #: 2900-0074
REQUEST FOR CHANGE OF BENEFIT, PROGRAM OR PLACE OF TRAINING
FOR VETERANS, SERVICEPERSONS, DEPENDENTS & MEMBERS OF THE SELECTED RESERVE
-------------------------------------
APPLICANT INFORMATION
---------------------
SSN: <%= value_or_na(@applicant.veteranSocialSecurityNumber) %> VA File Number: <%= value_or_na(@applicant.vaFileNumber) %>
<% if @applicant.minorHighSchoolQuestions -%>
Applicant has graduated high school or received GED? <%= @applicant.minorHighSchoolQuestions.minorHighSchoolQuestion %>
<% grad_date = @applicant.minorHighSchoolQuestions.highSchoolGedGradDate if @applicant.minorHighSchoolQuestions.highSchoolGedGradDate -%>
<% grad_date = @applicant.minorHighSchoolQuestions.highSchoolGedExpectedGradDate unless @applicant.minorHighSchoolQuestions.highSchoolGedGradDate -%>
<% date_label = @applicant.minorHighSchoolQuestions.highSchoolGedGradDate ? "Date graduated:" : "Date expected to graduate:" -%>
<%= date_label %> <%= grad_date %>
<% end -%>
Sex: <%= @applicant.applicantGender %> Date of Birth: <%= @applicant.dateOfBirth %>
Name: <%= full_name(@applicant.veteranFullName) %>
Address:
<%= full_address(@applicant.veteranAddress) %>
<%= parse_with_template_path('phone_numbers') %>
Email Address: <%= @applicant.email %>
Preferred Method of Contact: <%= @applicant.preferredContactMethod %>
<%= parse_with_template_path('bank_account_no_stop') %>
<% if @applicant.benefitUpdate.eql?('chapter35') || @applicant.benefitAppliedFor.eql?('chapter35') -%>
DEA, CH35 SPONSOR/SERVICE MEMBER INFORMATION
--------------------------------------------
Name: <%= full_name(@applicant.sponsorFullName) %>
SSN: <%= @applicant.sponsorSocialSecurityNumber %>
VA File Number: <%= value_or_na(@applicant.vaFileNumber) %>
<% end -%>
TYPE AND PROGRAM OF EDUCATION OR TRAINING
-----------------------------------------
Benefit Most Recently Received: <%= form_benefit %>
Do you wish to request a 'Rudisill' review?: <%= @applicant.rudisillReview %>
Select Another Benefit: <%= @applicant.changeAnotherBenefit %>
Benefit Being Applied For: <%= @applicant.benefitAppliedFor&.titleize %>
Type of Education or Training: <%= @applicant.educationTypeUpdate&.titleize %>
Education or Career Goal: <%= @applicant.educationObjective %>
New School or Training Establishment:
<%= school_name_and_addr(@applicant.newSchool) %>
APPLICANT ACTIVE DUTY SERVICE INFORMATION
-----------------------------------------
Served in the armed forces?: <%= @applicant.applicantServed %>
Are You Now On Active Duty?: <%= yesno(@applicant.isActiveDuty) %>
Do you have any new periods of service to record since you last applied for
education benefits? <%= yesno(@applicant.toursOfDuty.present?) %>
Date Entered Date Separated Service Component
<% @applicant&.toursOfDuty&.each do |tour| -%>
<%= to_date(tour.dateRange&.from) %> <%= to_date(tour.dateRange&.to) %> <%= tour.serviceBranch %>
<% end -%>
<% if @applicant.minorHighSchoolQuestions -%>
GUARDIAN INFORMATION
--------------------
First name of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianFirstName %>
Middle name of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianMiddleName %>
Last name of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianLastName %>
Suffix of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianSuffix %>
Address of Parent, Guardian or Custodian:
Country: <%= @applicant.minorQuestions.guardianAddress.country %>
Street: <%= @applicant.minorQuestions.guardianAddress.street %>
Street address line 2: <%= @applicant.minorQuestions.guardianAddress.street2 %>
City: <%= @applicant.minorQuestions.guardianAddress.city %>
State: <%= @applicant.minorQuestions.guardianAddress.state %>
Postal code: <%= @applicant.minorQuestions.guardianAddress.postalCode %>
Mobile phone number: <%= @applicant.minorQuestions.guardianMobilePhone %>
Home phone number: <%= @applicant.minorQuestions.guardianHomePhone %>
Email address: <%= @applicant.minorQuestions.guardianEmail %>
<% end -%>
<% if @applicant.isActiveDuty -%>
As an active-duty service member, you have consulted with an Education Service
Officer (ESO) regarding your education program.
<% else -%>
<% if @applicant.minorHighSchoolQuestions -%>
You are the parent, guardian, or custodian of the applicant
<% else -%>
Certification and Signature of Applicant
<% end -%>
Signature of Applicant Date
<% end -%>
<%= parse_with_template_path('footer') %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/signatures.erb
|
Certification and Signature of Applicant
Signature of Applicant Date
Certification for Persons on Active Duty
Signature/Title/Branch of Armed Forces Education Service Officer Date
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/1990.erb
|
<%= header %>
<%= benefit_type(@applicant) %>
*START*
VA Form 22-1990
OMB Control #: 2900-0154
APPLICATION FOR VA EDUCATION BENEFITS
-------------------------------------
<%= disclosures(@applicant) %>
APPLICANT INFORMATION
---------------------
<%= ssn_gender_dob %>
<% if @applicant.minorHighSchoolQuestions -%>
Applicant has graduated high school or received GED? <%= @applicant.minorHighSchoolQuestions.minorHighSchoolQuestion %>
<% grad_date = @applicant.minorHighSchoolQuestions.highSchoolGedGradDate if @applicant.minorHighSchoolQuestions.highSchoolGedGradDate -%>
<% grad_date = @applicant.minorHighSchoolQuestions.highSchoolGedExpectedGradDate unless @applicant.minorHighSchoolQuestions.highSchoolGedGradDate -%>
<% date_label = @applicant.minorHighSchoolQuestions.highSchoolGedGradDate ? "Date graduated:" : "Date expected to graduate:" -%>
<%= date_label %> <%= grad_date %>
<% end -%>
Name: <%= full_name(@applicant.veteranFullName) %>
Address:
<%= full_address(@applicant.veteranAddress) %>
<%= parse_with_template_path('phone_numbers') %>
Email Address: <%= @applicant.email %>
Preferred Method of Contact: <%= @applicant.preferredContactMethod %>
<%= parse_with_template_path('bank_account') %>
ACTIVE DUTY SERVICE INFORMATION
-------------------------------
Are You Now On Active Duty? <%= yesno(@applicant.currentlyActiveDuty&.yes) %>
Are you Now On Terminal Leave Just Before Discharge? <%= yesno(@applicant.currentlyActiveDuty&.onTerminalLeave) %>
<%= parse_with_template_path('tours_of_duty') %>
ENTITLEMENT TO AND USAGE OF ADDITIONAL TYPES OF ASSISTANCE
----------------------------------------------------------
Did you make additional contributions (up to $600) to increase the amount
of your monthly benefits? <%= yesno(@applicant.additionalContributions) %>
Do you qualify for a Kicker (sometimes called a College Fund) based on
your military service?
Active Duty Kicker: <%= yesno(@applicant.activeDutyKicker) %>
Reserve Kicker: <%= yesno(@applicant.reserveKicker) %>
If you graduated from a military service academy, specify the year you graduated and received your commission: <%= @applicant.serviceAcademyGraduationYear %>
ROTC Scholarship Program and Officer's Commission. Were you commissioned as the result of a Senior ROTC (Reserve Officers Training Corps) Scholarship Program? <%= yesno(@applicant.seniorRotc.present?) %>
Year of Commission: <%= @applicant.seniorRotc&.commissionYear %>
Scholarship Amounts:
<%= rotc_scholarship_amounts(@applicant.seniorRotc&.rotcScholarshipAmounts) %>
Senior ROTC Scholarship Program. Are you currently participating in a Senior ROTC Scholarship Program which pays for your tuition, fees, books and supplies under Section 2107, Title 10 U.S. Code? <%= yesno(@applicant.seniorRotcScholarshipProgram) %>
Did you have a period of active duty that the Department of Defense counts for purposes of repaying an education loan? <%= yesno(@applicant.activeDutyRepayingPeriod.present?) %>
Start Date: <%= to_date(@applicant.activeDutyRepayingPeriod&.from) %>
End Date: <%= to_date(@applicant.activeDutyRepayingPeriod&.to) %>
<% if @applicant.minorHighSchoolQuestions -%>
GUARDIAN INFORMATION
--------------------
First name of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianFirstName %>
Middle name of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianMiddleName %>
Last name of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianLastName %>
Address of Parent, Guardian or Custodian:
Country: <%= @applicant.minorQuestions.guardianAddress.country %>
Street: <%= @applicant.minorQuestions.guardianAddress.street %>
Street address line 2: <%= @applicant.minorQuestions.guardianAddress.street2 %>
City: <%= @applicant.minorQuestions.guardianAddress.city %>
State: <%= @applicant.minorQuestions.guardianAddress.state %>
Postal code: <%= @applicant.minorQuestions.guardianAddress.postalCode %>
Mobile phone number: <%= @applicant.minorQuestions.guardianMobilePhone %>
Home phone number: <%= @applicant.minorQuestions.guardianHomePhone %>
Email address: <%= @applicant.minorQuestions.guardianEmail %>
<% end -%>
<% if yesno(@applicant.currentlyActiveDuty&.yes).eql?('YES') -%>
As an active-duty service member, you have consulted with an Education Service Officer (ESO) regarding your education program.
<% else -%>
Certification and Signature of Applicant
Signature of Applicant Date
<% end -%>
<%= parse_with_template_path('footer') %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/tours_of_duty.erb
|
Date Entered Date Separated Service Component
Active Duty From Active Duty
<% @applicant&.toursOfDuty&.each do |tour| -%>
<%= tour.dateRange.from %> <%= tour.dateRange.to %> <%= tour.serviceBranch %>
Service Status: <%= tour.serviceStatus %>
Involuntary Call: <%= tour.involuntarilyCalledToDuty %>
<% if tour.benefitsToApplyTo.present? -%>
Benefits to Apply to: <%= tour.benefitsToApplyTo %>
<% end -%>
<% end %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/bank_account_no_stop.erb
|
<% bank_account_change = @applicant.bankAccountChangeUpdate -%>
<% if bank_account_change.present? -%>
Direct Deposit: <%= direct_deposit_type(bank_account_change) %> EFT
Type of Account: <%= @applicant.bankAccount&.accountType %>
<% else -%>
Direct Deposit: Type of Account: <%= @applicant.bankAccount&.accountType %>
<% end -%>
Routing/Transit #: <%= @applicant.bankAccount&.routingNumber %> Account #: <%= @applicant.bankAccount&.accountNumber %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/phone_numbers.erb
|
Telephone Numbers: Mobile: <%= @applicant.mobilePhone %>
Home: <%= @applicant.homePhone %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/school.erb
|
Name and Address of School or Training Establishment:
<%= school&.name %>
<%= full_address(school&.address, indent: true) %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/5495.erb
|
<%= header %>
<%= benefit_type(@applicant) %>
*START*
VA Form 22-5495
DEC 2016
DEPENDENTS' REQUEST FOR CHANGE OF PROGRAM OR PLACE OF TRAINING
(Under Provisions of Chapters 33 and 35, Title 38, U.S.C.)
-----------------------------------------------------------
APPLICANT INFORMATION
---------------------
<%= ssn_gender_dob(false) %>
VA File Number: <%= @applicant.relativeVaFileNumber %>
Name: <%= full_name(@applicant.relativeFullName) %>
Address:
<%= full_address(@applicant.relativeAddress) %>
<%= parse_with_template_path('phone_numbers') %>
Email Address: <%= @applicant.email %>
Preferred Method of Contact: <%= @applicant.preferredContactMethod %>
<%= parse_with_template_path('bank_account') %>
TYPE AND PROGRAM OF EDUCATION OR TRAINING
-----------------------------------------
Benefit You Are Receiving: <%= @applicant.benefit&.titleize %>
Type of Education or Training: <%= @applicant.educationProgram&.educationType&.titleize %>
Education or Career Goal: <%= @applicant.educationObjective %>
What is the name of the program you are requesting to pursue?: <%= @applicant.programName %>
New School or Training Establishment:
<%= school_name_and_addr(@applicant.educationProgram) %>
Current/Prior School or Training Establishment:
<%= school_name_and_addr(@applicant.oldSchool) %>
Date You Stopped Training: <%= @applicant.trainingEndDate %>
Reason for Change: <%= @applicant.reasonForChange %>
ACTIVE DUTY SERVICE INFORMATION
-------------------------------
Served on active duty?: <%= yesno(@applicant.toursOfDuty.present?) %>
<%= parse_with_template_path('tours_of_duty') %>
SERVICE MEMBER INFORMATION
--------------------------
Name: <%= full_name(@applicant.veteranFullName) %>
SSN: <%= @applicant.veteranSocialSecurityNumber %>
VA File Number: <%= @applicant.vaFileNumber %>
Outstanding felony or warrant: <%= yesno(@applicant.outstandingFelony) %>
Remarks: <%= @applicant.remarks %>
<%= parse_with_template_path('signatures') %>
<%= parse_with_template_path('footer') %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/10297.erb
|
<%= header %>
<%= benefit_type %>
*START*
VA Form 22-10297
JAN 2019
APPLICATION FOR VETERAN EMPLOYMENT THROUGH TECHNOLOGY EDUCATION COURSES
(VET TEC) HIGH TECHNOLOGY PROGRAM
-------------------------------------------------------
APPLICANT INFORMATION
---------------------
Name: <%= full_name(@applicant.applicantFullName) %>
Social Security Number: <%= @applicant.ssn %>
Mailing Address:
<%= full_address_with_street2(@applicant.mailingAddress) %>
Date of Birth: <%= @applicant.dateOfBirth %>
Email Address: <%= @applicant.contactInfo.emailAddress %>
Mobile Telephone Number: <%= @applicant.contactInfo.mobilePhone %>
Home Telephone Number: <%= @applicant.contactInfo.homePhone %>
Are you a veteran who has completed 3 years (36 months) of active duty?: <%= yesno(@applicant.veteranStatus) %>
Enter the date you expect to be released from active duty: <%= @applicant.dateReleasedFromActiveDuty %>
Do you expect to be called to active duty while enrolled
in a VET TEC program?: <%= yesno_or_blank(@applicant.activeDutyDuringHitechVets) %>
DIRECT DEPOSIT INFORMATION:
Routing or Transit Number: <%= bank_routing_number %>
Account Type: <%= bank_account_type %>
Account Number: <%= bank_account_number %>
COURSE OF STUDY
---------------
VET TEC programs:
<%= program_text %>
BACKGROUND INFORMATION
----------------------
Are you working in one, or more, of these high-tech industries now?: <%= yesno(@applicant.isInTechnologyIndustry) %>
Which option(s) best describe your high-tech work experience?
Check all that apply:
<%= high_tech_area_name %>
About how much per year do/did you earn as a high-tech worker?: <%= salary_text %>
What is your highest level of education?: <%= education_level_name %>
<%= parse_with_template_path('footer') %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/civilian_benefits_assistance.erb
|
For Civilian Employees of the U.S. Federal Government Only. Are you receiving or do you anticipate receiving any money from your agency (including but not limited to the Government Employees Training Act) for the same period for which you have applied to the VA for Education Benefits? If you will receive such benefits during any part of your training, check Yes. <%= yesno(@applicant.civilianBenefitsAssistance) %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/header_1995.erb
|
*INIT*
<%= applicant_name&.first&.upcase&.strip %>
<%= applicant_name&.middle&.upcase&.strip %>
<%= applicant_name&.last&.upcase&.strip %>
<% if @applicant.benefitAppliedFor.eql?('chapter35') || (@applicant.benefitAppliedFor.blank? && @applicant.benefitUpdate.eql?('chapter35')) -%>
<%= @applicant.sponsorSocialSecurityNumber&.gsub(/[^\d]/, '') %>
<% else -%>
<%= @applicant.veteranSocialSecurityNumber&.gsub(/[^\d]/, '') %>
<% end -%>
<%= @applicant.veteranSocialSecurityNumber&.gsub(/[^\d]/, '') %>
<%= header_form_type %>
<%= school_name %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/5490.erb
|
<%= header %>
<%= benefit_type(@applicant) %>
*START*
VA Form 22-5490
OMB Control #: 2900-0098
DEPENDENTS APPLICATION FOR EDUCATION BENEFITS
(Under Provisions of chapters 33 and 35 of Title 38, U.S.C)
-----------------------------------------------------------
BENEFIT ELECTION
----------------
EDUCATION BENEFIT BEING APPLIED FOR: <%= @applicant.benefit %>
<%
case
-%>
<% when @applicant.benefit == 'chapter35' && @applicant.relationshipAndChildType == 'spouse' -%>
I UNDERSTAND THAT I AM CHOOSING TO RECEIVE DEA BENEFITS INSTEAD OF ANY FRY SCHOLARSHIP BENEFITS FOR WHICH I AM CURRENTLY ELIGIBLE. THIS INCLUDES FRY SCHOLARSHIP BENEFITS BASED ON THE DEATH OF THE QUALIFYING INDIVIDUAL ON THIS APPLICATION, AS WELL AS, FRY SCHOLARSHIP BENEFITS BASED ON THE DEATH OF ANY OTHER INDIVIDUALS NOT LISTED ON THIS APPLICATION.
<% when @applicant.benefit == 'chapter35' && ['biological','step','adopted'].include?(@applicant.relationshipAndChildType) -%>
I UNDERSTAND THAT I’M CHOOSING TO RECEIVE DEA BENEFITS INSTEAD OF ANY FRY SCHOLARSHIP BENEFITS BASED ON THE DEATH OF THE QUALIFYING INDIVIDUAL ON THIS APPLICATION. I UNDERSTAND THAT EVEN AFTER THIS CHOICE I’LL CONTINUE TO BE ELIGIBLE FOR FRY SCHOLARSHIP BENEFITS IF MY ELIGIBILITY IS BASED ON THE DEATH OF THE QUALIFYING INDIVIDUAL ON THIS APPLICATION, AND THEY DIED BEFORE AUGUST 1, 2011.
<% when @applicant.benefit == 'chapter33' && @applicant.relationshipAndChildType == 'spouse' -%>
I UNDERSTAND THAT I AM CHOOSING TO RECEIVE FRY SCHOLARSHIP BENEFITS INSTEAD OF ANY DEA BENEFITS FOR WHICH I AM CURRENTLY ELIGIBLE. THIS INCLUDES DEA BENEFITS BASED ON THE DEATH OF THE QUALIFYING INDIVIDUAL ON THIS APPLICATION, BASED ON THE DEATH OF ANY OTHER INDIVIDUALS NOT LISTED ON THIS APPLICATION, BASED ON A SPOUSE WHO HAS A PERMANENT AND TOTAL SERVICE-CONNECTED DISABILITY, OR BASED ON ANY OTHER CRITERIA AS LISTED IN 38 U.S.C. SECTION 3501(A)(1).
<% when @applicant.benefit == 'chapter33' && ['biological','step','adopted'].include?(@applicant.relationshipAndChildType) -%>
I UNDERSTAND THAT I’M CHOOSING TO RECEIVE FRY SCHOLARSHIP BENEFITS INSTEAD OF DEA BENEFITS FOR WHICH I’M CURRENTLY ELIGIBLE BASED ON THE DEATH OF THE QUALIFYING INDIVIDUAL ON THIS APPLICATION. I UNDERSTAND THAT EVEN AFTER THIS CHOICE I’LL CONTINUE TO BE ELIGIBLE FOR DEA BENEFITS IF MY ELIGIBILITY IS BASED ON:
* THE DEATH OF THE QUALIFYING INDIVIDUAL ON THIS APPLICATION, AND THEY DIED BEFORE AUGUST 1, 2011, OR
* A PARENT WHO HAS A PERMANENT AND TOTAL SERVICE-CONNECTED DISABILITY, OR
* Any other criteria as listed in 38 U.S.C. SECTION 3501(a)(1)
<% end -%>
<% if @applicant.benefitsRelinquishedDate.present? -%>
I CERTIFY THAT I UNDERSTAND THE EFFECTS THAT THIS ELECTION TO RECEIVE DEA OR FRY SCHOLARSHIP BENEFITS WILL HAVE ON MY ELIGIBILITY TO RECEIVE DIC, AND I ELECT TO RECEIVE SUCH EDUCATION BENEFITS ON THE FOLLOWING DATE: <%= to_date(@applicant.benefitsRelinquishedDate) %>
<% end -%>
Restorative training: <%= yesno(@applicant.restorativeTraining) %>
Vocational training: <%= yesno(@applicant.vocationalTraining) %>
Would you like to receive vocational and educational counseling?: <%= yesno(@applicant.educationalCounseling) %>
APPLICANT INFORMATION
---------------------
<%= ssn_gender_dob(false) %>
<% if @applicant.minorHighSchoolQuestions -%>
Applicant has graduated high school or received GED? <%= @applicant.minorHighSchoolQuestions.minorHighSchoolQuestion %>
<% grad_date = @applicant.minorHighSchoolQuestions.highSchoolGedGradDate if @applicant.minorHighSchoolQuestions.highSchoolGedGradDate -%>
<% grad_date = @applicant.minorHighSchoolQuestions.highSchoolGedExpectedGradDate unless @applicant.minorHighSchoolQuestions.highSchoolGedGradDate -%>
<% date_label = @applicant.minorHighSchoolQuestions.highSchoolGedGradDate ? "Date graduated:" : "Date expected to graduate:" -%>
<%= date_label %> <%= grad_date %>
<% end -%>
Name: <%= full_name(@applicant.relativeFullName) %>
Address:
<%= full_address(@applicant.relativeAddress) %>
<%= parse_with_template_path('phone_numbers') %>
Email Address: <%= @applicant.email %>
Preferred Method of Contact: <%= @applicant.preferredContactMethod %>
<%= parse_with_template_path('bank_account') %>
<% if @applicant.relationshipAndChildType.eql?('spouse') -%>
Relationship to service member: <%= @applicant.relationshipAndChildType.upcase if @applicant.relationshipAndChildType %>
<% else %>
Relationship to service member: <%= @applicant.relationshipAndChildType.capitalize + ' Child' if @applicant.relationshipAndChildType %>
<% end -%>
<% if @applicant.spouseInfo.present? -%>
Married date: <%= to_date(@applicant.spouseInfo.marriageDate) %>
Is a divorce or annulment pending?: <%= yesno(@applicant.spouseInfo.divorcePending) %>
Have you remarried since the death of the veteran?: <%= yesno(@applicant.spouseInfo.remarried) %>
Remarried date: <%= to_date(@applicant.spouseInfo.remarriageDate) %>
<% end -%>
SERVICE MEMBER INFORMATION
--------------------------
Name: <%= full_name(@applicant.veteranFullName) %>
SSN: <%= @applicant.veteranSocialSecurityNumber %>
VA File Number: <%= value_or_na(@applicant.vaFileNumber) %>
Branch of Service: <%= @applicant.serviceBranch %>
Veteran's date of birth: <%= @applicant.veteranDateOfBirth %>
<%= veteran_date_of_death_label %>
<%= value_or_na(@applicant.veteranDateOfDeath) %>
Is qualifying individual on active duty: <%= yesno(@applicant.currentlyActiveDuty) %>
Outstanding felony or warrant: <%= yesno(@applicant.outstandingFelony) %>
APPLICATION HISTORY
-------------------
Previously applied for VA benefits? <%= yesno(previously_applied_for_benefits?) %>
Previously claimed benefits:
<%= previous_benefits %>
Name of individual on whose account previously claimed: <%= full_name(@applicant.previousBenefits&.veteranFullName) %>
SSN of individual on whose account previously claimed: <%= @applicant.previousBenefits&.veteranSocialSecurityNumber %>
VA File Number for previously claimed benefits: <%= @applicant.previousBenefits&.vaFileNumber %>
ACTIVE DUTY SERVICE INFORMATION
-------------------------------
Served on active duty?: <%= yesno(@applicant.toursOfDuty.present?) %>
<%= parse_with_template_path('tours_of_duty') %>
<% if @applicant.minorHighSchoolQuestions -%>
GUARDIAN INFORMATION
--------------------
First name of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianFirstName %>
Middle name of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianMiddleName %>
Last name of Parent, Guardian or Custodian: <%= @applicant.minorQuestions.guardianLastName %>
Address of Parent, Guardian or Custodian:
Country: <%= @applicant.minorQuestions.guardianAddress.country %>
Street: <%= @applicant.minorQuestions.guardianAddress.street %>
Street address line 2: <%= @applicant.minorQuestions.guardianAddress.street2 %>
City: <%= @applicant.minorQuestions.guardianAddress.city %>
State: <%= @applicant.minorQuestions.guardianAddress.state %>
Postal code: <%= @applicant.minorQuestions.guardianAddress.postalCode %>
Mobile phone number: <%= @applicant.minorQuestions.guardianMobilePhone %>
Home phone number: <%= @applicant.minorQuestions.guardianHomePhone %>
Email address: <%= @applicant.minorQuestions.guardianEmail %>
<% end -%>
<% if @applicant.currentlyActiveDuty -%>
As an active-duty service member, you have consulted with an Education Service
Officer (ESO) regarding your education program.
<% else -%>
Certification and Signature of Applicant
Signature of Applicant Date
<% end -%>
<%= parse_with_template_path('footer') %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/0994.erb
|
<%= header %>
<%= benefit_type %>
*START*
VA Form 22-0994
JAN 2019
APPLICATION FOR VETERAN EMPLOYMENT THROUGH TECHNOLOGY EDUCATION COURSES
(VET TEC) HIGH TECHNOLOGY PROGRAM
-------------------------------------------------------
APPLICANT INFORMATION
---------------------
Name: <%= full_name(@applicant.applicantFullName) %>
Social Security Number: <%= @applicant.applicantSocialSecurityNumber %>
Mailing Address:
<%= full_address_with_street3(@applicant.mailingAddress) %>
Sex of Applicant: <%= @applicant.applicantGender %>
Date of Birth: <%= @applicant.dateOfBirth %>
Email Address: <%= @applicant.emailAddress %>
Mobile Telephone Number: <%= @applicant.mobilePhone %>
Home Telephone Number: <%= @applicant.homePhone %>
Have you ever applied for VA education benefits?: <%= yesno(@applicant.appliedForVaEducationBenefits) %>
Are you on full-time duty in the Armed Forces? (This doesn't
include active-duty training for Reserve and National Guard members.): <%= yesno(@applicant.activeDuty) %>
Enter the date you expect to be released from active duty: <%= @applicant.expectedReleaseDate %>
Do you expect to be called to active duty while enrolled
in a VET TEC program?: <%= yesno_or_blank(@applicant.expectedActiveDutyStatusChange) %>
DIRECT DEPOSIT INFORMATION:
Routing or Transit Number: <%= bank_routing_number %>
Account Type: <%= bank_account_type %>
Account Number: <%= bank_account_number %>
COURSE OF STUDY
---------------
VET TEC programs:
<%= program_text %>
BACKGROUND INFORMATION
----------------------
Are you working in one, or more, of these high-tech industries now?: <%= yesno(@applicant.currentHighTechnologyEmployment) %>
Have you worked in any of these high-tech industries in the past?: <%= yesno(@applicant.pastHighTechnologyEmployment) %>
Which option(s) best describe your high-tech work experience?
Check all that apply:
<%= high_tech_area_names %>
About how much per year do/did you earn as a high-tech worker?: <%= salary_text %>
What is your highest level of education?: <%= education_level_name %>
<%= parse_with_template_path('footer') %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/secondary_contact.erb
|
Name, Address, & Telephone Number of Contact:
<%= @applicant.secondaryContact&.fullName %>
<%- if @applicant.secondaryContact&.sameAddress -%>
Address same as claimant
<%- else -%>
<%= full_address(@applicant.secondaryContact&.address, indent: true) %>
<%- end -%>
Phone: <%= @applicant.secondaryContact&.phone %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/0993.erb
|
<%= header %>
*START*
VA Form 22-0993
AUG 2018
REQUEST TO OPT-OUT OF INFORMATION SHARING WITH EDUCATIONAL INSTITUTIONS
-------------------------------------
APPLICANT INFORMATION
---------------------
SSN: <%= value_or_na(@applicant.claimantSocialSecurityNumber) %>
VA File Number: <%= value_or_na(@applicant.vaFileNumber) %>
Name: <%= full_name(@applicant.claimantFullName) %>
I CERTIFY THAT the Department of Veterans Affairs (VA) does not have my permission, to share my personally identifiable information or information about my veterans' education benefits with any educational institution. I am asserting my rights under 38 U.S.C. 3699A(b) to opt-out of any sharing of this information by the Department of Veterans Affairs.
Certification and Signature of Applicant
Signature of Applicant Date
<%= parse_with_template_path('footer') %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form
|
code_files/vets-api-private/app/sidekiq/education_form/templates/bank_account.erb
|
<% bank_account_change = @applicant.bankAccountChange -%>
<% if bank_account_change.present? -%>
Direct Deposit: <%= direct_deposit_type(bank_account_change) %> EFT
Type of Account: <%= @applicant.bankAccount&.accountType %>
<% else -%>
Direct Deposit: Type of Account: <%= @applicant.bankAccount&.accountType %>
<% end -%>
Name of Financial Inst.: <%= @applicant.bankAccount&.bankName %>
Routing/Transit #: <%= @applicant.bankAccount&.routingNumber %> Account #: <%= @applicant.bankAccount&.accountNumber %>
|
0
|
code_files/vets-api-private/app/sidekiq/education_form/templates
|
code_files/vets-api-private/app/sidekiq/education_form/templates/1990-disclosure/_CH1606.erb
|
EDUCATION BENEFIT BEING APPLIED FOR: Chapter 1606
|
0
|
code_files/vets-api-private/app/sidekiq/education_form/templates
|
code_files/vets-api-private/app/sidekiq/education_form/templates/1990-disclosure/_CH30.erb
|
EDUCATION BENEFIT BEING APPLIED FOR: Chapter 30
|
0
|
code_files/vets-api-private/app/sidekiq/education_form/templates
|
code_files/vets-api-private/app/sidekiq/education_form/templates/1990-disclosure/_CH32.erb
|
EDUCATION BENEFIT BEING APPLIED FOR: Chapter 32
|
0
|
code_files/vets-api-private/app/sidekiq/education_form/templates
|
code_files/vets-api-private/app/sidekiq/education_form/templates/1990-disclosure/_CH33.erb
|
EDUCATION BENEFIT BEING APPLIED FOR: Chapter 33
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.