Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Letter of support - upload form #697

Merged
merged 8 commits into from
Jul 18, 2024
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -7,33 +7,36 @@ window.SupportLetters =
new_item_init: (el) ->
SupportLetters.clean_up_system_tags(el)
SupportLetters.enable_item_fields_and_controls(el)
SupportLetters.fileupload_init(el.find(".js-support-letter-attachment"))
SupportLetters.fileupload_init(el.find('.js-support-letter-attachment'))
el.find('input,textarea,select').first().focus()

fileupload_init: (el) ->
$el = $(el)
parent = $el.closest(".govuk-form-group")
parent = $el.closest('.govuk-form-group')

upload_done = (e, data) ->
SupportLetters.clean_up_system_tags(parent)

if data.result['original_filename']
filename = data.result['original_filename']
else
filename = "File uploaded"
file_title = $("<p class='govuk-body support-letter-attachment-filename'>" + filename + "</p>")
hidden_input = $("<input class='js-support-letter-attachment-id' type='hidden' name='#{$el.attr("name")}' value='#{data.result['id']}' />")

parent.find(".govuk-error-message").html("")
parent.find(".govuk-error-message").closest(".govuk-form-group").removeClass("govuk-form-group--error")
parent.append(file_title)
parent.append(hidden_input)
filename = 'File uploaded'

parent.find('.govuk-error-message').html('')
parent.find('.govuk-error-message').closest('.govuk-form-group').removeClass('govuk-form-group--error')

label = $('<p class="govuk-body support-letter-attachment-filename">' + filename + '</p>')
hiddenInput = $("<input class='js-support-letter-attachment-id' type='hidden' name='#{$el.attr("name")}' value='#{data.result['id']}' />")

parent.append(label)
parent.append(hiddenInput)
SupportLetters.autosave()
SupportLetters.submit(e)

failed = (error_message) ->
SupportLetters.clean_up_system_tags(parent)
parent.find(".govuk-error-message").html(error_message)
parent.closest(".govuk-form-group").addClass("govuk-form-group--error")
parent.find('.govuk-error-message').html(error_message)
parent.closest('.govuk-form-group').addClass('govuk-form-group--error')

success_or_error = (e, data) ->
errors = data.result.errors
Expand All @@ -44,108 +47,33 @@ window.SupportLetters =
upload_done(e, data)

$el.fileupload(
url: $el.closest(".list-add").data('attachments-url') + ".json"
url: $el.closest('.list-add').data('attachments-url') + '.json'
forceIframeTransport: true
dataType: 'json'
formData: [
{ name: "authenticity_token", value: $("meta[name='csrf-token']").attr("content") }
{ name: 'authenticity_token', value: $('meta[name="csrf-token"]').attr('content') }
]
always: success_or_error
)

clean_up_system_tags: (parent) ->
parent.find("input[type='hidden']").remove()
parent.find(".support-letter-attachment-filename").remove()
parent.find('input[type="hidden"]').remove()
parent.find('.support-letter-attachment-filename').remove()

enable_item_fields_and_controls: (parent) ->
parent.find(".js-save-collection").removeClass("govuk-!-display-none")
parent.find(".visible-read-only").hide()
fields = parent.find("input")
fields.removeClass("read-only")
parent.find(".govuk-error-message").html("")
form_name_prefix = parent.find(".js-system-tag").data("new-hidden-input-name")
letter_id_hidden_input = $("<input class='js-support-entry-id'>").prop('type', 'hidden').
prop('name', form_name_prefix)
parent.append(letter_id_hidden_input)

disable_item_fields_and_controls: (parent) ->
parent.find(".js-save-collection").addClass("govuk-!-display-none")
parent.find(".visible-read-only").show()
fields = parent.find("input")
fields.addClass("read-only")
parent.find('.govuk-error-message').html('')
prefixed = parent.find('.js-system-tag').data('new-hidden-input-name')
hiddenInput = $('<input class="js-support-entry-id">').prop('type', 'hidden').prop('name', prefixed)
parent.append(hiddenInput)

save_collection_init: () ->
$(document).on 'click', '.js-save-collection', (e) ->
e.preventDefault()
e.stopPropagation()

button = $(this)
parent = $(this).closest("li")

if !button.hasClass("govuk-!-display-none")
save_url = button.data 'save-collection-url'

first_name = parent.find(".js-support-letter-first-name").val()
last_name = parent.find(".js-support-letter-last-name").val()
email = parent.find(".js-support-letter-email").val()
relationship_to_nominee = parent.find(".js-support-letter-relationship-to-nominee").val()
attachment_id = parent.find(".js-support-letter-attachment-id").val()

data = {
"support_letter": {
"first_name": first_name,
"last_name": last_name,
"relationship_to_nominee": relationship_to_nominee
}
}

if attachment_id
data["support_letter"]["attachment"] = attachment_id

if email
data["support_letter"]["email"] = email

if save_url
$.ajax
url: save_url
type: 'post'
data: data
dataType: 'json'
success: (response) ->
parent.find(".js-support-entry-id").prop('value', response)
parent.find(".govuk-error-message").html("")
parent.removeClass("govuk-form-group--error")
parent.addClass("read-only")
parent.addClass("js-support-letter-received")
parent.closest('li').find("input[type='text']").each ->
show_el = $(this).closest(".govuk-form-group").find(".visible-read-only")
show_el.text($(this).val())
SupportLetters.disable_item_fields_and_controls(parent)
window.FormValidation.validateStep()
SupportLetters.autosave()
SupportLetters.showRemoveLink(parent, data, response)

return
error: (response) ->
parent.find(".govuk-error-message").html("")
parent.removeClass("govuk-form-group--error")
error_message = response.responseText
$.each $.parseJSON(response.responseText), (question_key, error_message) ->
key_selector = ".js-support-letter-" + question_key.replace(/_/g, "-")
field_error_container = parent.find(key_selector).
closest(".govuk-form-group").
find(".govuk-error-message")
field_error_container.html(error_message[0])
field_error_container.closest(".govuk-form-group").addClass("govuk-form-group--error")
button.removeClass("govuk-visually-hidden")

return
$(document).on 'change', '.js-trigger-autosave', debounce(SupportLetters.submit, 1000)

autosave: () ->
url = $('form.qae-form').data('autosave-url')
if url
# Setting current_step_id to form as we updating only current section form_data (not whole form)
$("#current_step_id").val($(".js-step-condition.step-current").attr("data-step"))
$('#current_step_id').val($('.js-step-condition.step-current').attr('data-step'))

form_data = $('form.qae-form').serialize()
$.ajax({
Expand All @@ -155,8 +83,71 @@ window.SupportLetters =
dataType: 'json'
})

showRemoveLink: (parent, data, response) ->
removeLink = $(".remove-supporter", parent)
removeLink.data("url", "/users/form_answers/#{response['form_answer_id']}/support_letters/#{response['id']}")
removeLink.attr("aria-label", "Delete support letter from #{data['support_letter']['first_name']} #{data['support_letter']['last_name']}")
removeLink.removeClass("govuk-!-display-none")
submit: (e) ->
e.preventDefault()
e.stopPropagation()

target = $(e.target)
parent = target.closest("li")

data = {'support_letter': {}}
data['support_letter']['first_name'] = parent.find('.js-support-letter-first-name').val()
data['support_letter']['last_name'] = parent.find('.js-support-letter-last-name').val()
data['support_letter']['relationship_to_nominee'] = parent.find('.js-support-letter-relationship-to-nominee').val()

attachmentId = parent.find('.js-support-letter-attachment-id').val()
if attachmentId
data['support_letter']['attachment'] = attachmentId

email = parent.find('.js-support-letter-email').val()
if email
data['support_letter']['email'] = email

createUrl = parent.data('create-url')
updateUrl = parent.data('update-url')
persistUrl = updateUrl || createUrl

type = if !!updateUrl
'put'
else
'post'

if persistUrl
$.ajax
url: persistUrl
type: type
data: data
dataType: 'json'
success: (response) ->
parent.find('.js-support-entry-id').prop('value', response['id'])
parent.find('.govuk-error-message').html('')
parent.removeClass('govuk-form-group--error')
parent.addClass('js-support-letter-received')
parent.attr('data-update-url', response['update_url'])
window.FormValidation.validateStep()
SupportLetters.autosave()

return
error: (response) ->
parent.find('.govuk-error-message').html('')
parent.removeClass('govuk-form-group--error')
msg = response.responseText
$.each $.parseJSON(response.responseText), (key, msg) ->
selector = '.js-support-letter-' + key.replace(/_/g, '-')

errorContainer = parent.find(selector).closest('.govuk-form-group').find('.govuk-error-message')
errorContainer.html(msg[0])
errorContainer.closest('.govuk-form-group').addClass('govuk-form-group--error')

return

debounce = (fn, wait = 500) ->
last = (new Date) - wait
->
now = new Date

# Return if we haven't waited long enough
return if wait > (now - last)

fn.apply null, arguments
last = now
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

βœ‚οΈ

125 changes: 42 additions & 83 deletions app/controllers/form/support_letters_controller.rb
Original file line number Diff line number Diff line change
@@ -1,100 +1,59 @@
class Form::SupportLettersController < Form::BaseController
before_action :load_letter, only: :destroy
include FormAnswerSubmissionMixin

def create
@support_letter = @form_answer.support_letters.new(
support_letter_params.merge(
user_id: current_user.id,
manual: true
)
)

attachment = SupportLetterAttachment.new(attachment_params)
attachment.user = current_user
attachment.form_answer = @form_answer
attachment.original_filename = attachment_params[:attachment].try(:original_filename)
@support_letter.support_letter_attachment = attachment

if @support_letter.save
add_support_letter_to_document!
@form_answer.save

redirect_to form_form_answer_supporters_path(@form_answer)
@form_answer.support_letters_attributes = permitted_params["support_letters_attributes"]
@form_answer.document = prepare_doc if params[:form].present?

if @form_answer.valid? && @form_answer.save
add_support_letters_to_document!

if params[:next_step_id]
redirect_to edit_form_url(@form_answer, step: params[:next_step_id])
else
redirect_to form_form_answer_supporters_path(@form_answer)
end
else
render :new
end
end
@step = @form.steps.detect { |s| s.opts[:id] == :letters_of_support_step }

def new
@support_letter = @form_answer.support_letters.new
end

def destroy
# safeguard for the case when not a user tries to delete a letter
return if current_assessor || current_lieutenant

if @support_letter.destroy
remove_support_letter_from_document!
@form_answer.save
render "form/supporters/index"
end

redirect_to form_form_answer_supporters_path(@form_answer)
end

private

def support_letter_params
params[:support_letter].permit(
:first_name,
:last_name,
:relationship_to_nominee
def permitted_params
params.require(:form_answer).permit(
support_letters_attributes: [
:id,
:first_name,
:last_name,
:relationship_to_nominee,
:user_id,
:manual,
support_letter_attachment_attributes: [
:id,
:attachment,
:attachment_cache,
:form_answer_id,
:user_id
]
]
)
end

def attachment_params
if params[:support_letter] && params[:support_letter][:support_letter_attachment]
params[:support_letter][:support_letter_attachment].permit(:attachment)
else
{}
end
end

def load_letter
@support_letter = @form_answer.support_letters.find(params[:id])
end

def add_support_letter_to_document!
letters = support_letters_doc

new_letter = {
support_letter_id: @support_letter.id,
first_name: @support_letter.first_name,
last_name: @support_letter.last_name,
relationship_to_nominee: @support_letter.relationship_to_nominee,
letter_of_support: @support_letter.support_letter_attachment.id
}

letters << new_letter

@form_answer.document = @form_answer.document.merge(supporter_letters_list: letters,
manually_upload: "yes")
end

def remove_support_letter_from_document!
letters = support_letters_doc

letters.delete_if do |sup|
sup["support_letter_id"] == @support_letter.id
def add_support_letters_to_document!
list = @form_answer.support_letters.each_with_object([]) do |support_letter, memo|
memo << Hash[].tap do |h|
h[:support_letter_id] = support_letter.id
h[:first_name] = support_letter.first_name
h[:last_name] = support_letter.last_name
h[:relationship_to_nominee] = support_letter.relationship_to_nominee
h[:letter_of_support] = support_letter.support_letter_attachment.id
end
end

@form_answer.document = @form_answer.document.merge(supporter_letters_list: letters)
end

def support_letters_doc
if @form_answer.document["supporter_letters_list"].present?
@form_answer.document["supporter_letters_list"]
else
[]
end
@form_answer.document = @form_answer.document.merge(supporter_letters_list: list, manually_upload: "yes")
@form_answer.save!
end
end
Loading
Loading