diff --git a/app/models/concerns/account_settings.rb b/app/models/concerns/account_settings.rb index 4546a7421..85e9196bb 100644 --- a/app/models/concerns/account_settings.rb +++ b/app/models/concerns/account_settings.rb @@ -164,6 +164,8 @@ def validate_contact_emails def validate_json json_editor_settings.each do |key| + next unless settings[key].present? + begin JSON.parse(settings[key]) rescue JSON::ParserError => e diff --git a/spec/models/concerns/account_settings_spec.rb b/spec/models/concerns/account_settings_spec.rb index a41bce441..a63b14858 100644 --- a/spec/models/concerns/account_settings_spec.rb +++ b/spec/models/concerns/account_settings_spec.rb @@ -10,6 +10,7 @@ expect(account.public_settings(is_superadmin: true).keys.sort).to eq %i[allow_downloads allow_signup analytics_provider + bulkrax_field_mappings cache_api contact_email contact_email_to @@ -49,4 +50,66 @@ end end end + + describe '#bulkrax_field_mappings' do + context 'when the setting is blank' do + it 'returns the default field mappings configured in Bulkrax' do + expect(account.settings['bulkrax_field_mappings']).to be_nil + # For parity, parse Bulkrax field mappings from JSON. #to_json will stringify keys as + # well as turn a regex like /\|/ into (?-mix:\\|) + default_bulkrax_mappings = JSON.parse(Bulkrax.field_mappings.to_json) + default_tenant_mappings = JSON.parse(account.bulkrax_field_mappings) + + expect(default_tenant_mappings).to eq(default_bulkrax_mappings) + end + end + + context 'when the setting is present' do + let(:account) { build(:account, settings: { bulkrax_field_mappings: setting_value }) } + + context 'when the value is valid JSON' do + let(:setting_value) do + { + 'Bulkrax::CsvParser' => { + 'fake_field' => { from: %w[fake_column], split: /\s*[|]\s*/ } + } + }.to_json + end + + it 'parses the JSON into a Hash and prints it as pretty JSON' do + expect(account.bulkrax_field_mappings) + .to eq(JSON.pretty_generate(JSON.parse(setting_value))) + end + end + + context 'when the value is not valid JSON' do + let(:setting_value) { 'hello world' } + + it 'returns the raw value' do + expect(account.bulkrax_field_mappings).to eq(setting_value) + end + end + end + end + + describe '#validate_json' do + let(:account) { build(:account, settings: { bulkrax_field_mappings: setting_value }) } + + context 'when a "json_editor" setting is valid JSON' do + let(:setting_value) { { a: 'b' }.to_json } + + it 'does not error' do + expect(account.valid?).to eq(true) + end + end + + context 'when a "json_editor" setting is not valid JSON' do + let(:setting_value) { 'hello world' } + + it 'adds an error to the setting' do + expect(account.valid?).to eq(false) + expect(account.errors.messages[:bulkrax_field_mappings]).to eq(["unexpected token at 'hello world'"]) + end + end + end end