diff --git a/app/lib/upload_wrapper.rb b/app/lib/upload_wrapper.rb new file mode 100644 index 000000000..7392df414 --- /dev/null +++ b/app/lib/upload_wrapper.rb @@ -0,0 +1,14 @@ +class UploadWrapper + include ActiveSupport::NumberHelper + + attr_reader :upload + + def initialize(upload:) + @upload = upload + end + + def as_json(*args) + r = super + r.merge(file_size: number_to_human_size(upload.size, strip_insignificant_zeros: false)) + end +end diff --git a/app/models/concerns/validation_tracking.rb b/app/models/concerns/validation_tracking.rb index e5c33d86f..1e81320a6 100644 --- a/app/models/concerns/validation_tracking.rb +++ b/app/models/concerns/validation_tracking.rb @@ -41,6 +41,18 @@ def value_for_field(field) return if field == :base return if field.to_s.start_with?("section.") - public_send(field) + value = public_send(field) + + if value.instance_of?(Array) + value = value.map do |upload| + if upload.instance_of?(ActionDispatch::Http::UploadedFile) + UploadWrapper.new(upload:) + else + upload + end + end + end + + value end end diff --git a/spec/lib/upload_wrapper_spec.rb b/spec/lib/upload_wrapper_spec.rb new file mode 100644 index 000000000..4e1af2a0a --- /dev/null +++ b/spec/lib/upload_wrapper_spec.rb @@ -0,0 +1,15 @@ +require "rails_helper" + +RSpec.describe UploadWrapper do + describe "#as_json" do + subject(:upload_wrapper) do + described_class.new(upload:) + end + + let(:upload) { file_fixture("upload1.pdf") } + + it "includes file size" do + expect(upload_wrapper.as_json[:file_size]).to eql("4.98 KB") + end + end +end diff --git a/spec/models/concerns/validation_tracking_spec.rb b/spec/models/concerns/validation_tracking_spec.rb new file mode 100644 index 000000000..ebbaf8be6 --- /dev/null +++ b/spec/models/concerns/validation_tracking_spec.rb @@ -0,0 +1,42 @@ +require "rails_helper" + +RSpec.describe ValidationTracking do + let(:klass) do + Class.new do + include ActiveModel::Model + include ValidationTracking + + attr_accessor :evidence_uploads + + validate :field_with_meta_options + + def self.model_name + ActiveModel::Name.new(self, nil, "referrals/allegation_evidence/upload_form") + end + + def self.name + "Referrals::AllegationEvidence::UploadForm" + end + + def field_with_meta_options + errors.add(:evidence_uploads, :file_size_too_big, max_allowed_file_size: "50MB") + end + end + end + + describe "#track_validation_error" do + context "when an uploaded file" do + subject(:instance) do + klass.new(evidence_uploads: [ActionDispatch::Http::UploadedFile.new(tempfile: file_fixture("upload1.pdf"))]) + end + + it "persists the file size" do + expect { + instance.valid? + }.to change(ValidationError, :count).by(1) + + expect(ValidationError.last.details.dig("evidence_uploads", "value", 0, "file_size")).to eql("4.98 KB") + end + end + end +end