From 90f75cdce56072a304e0928b658cae95d964d7b1 Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:45:20 -0600 Subject: [PATCH 01/22] Create `doi.rake` --- lib/tasks/doi.rake | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 lib/tasks/doi.rake diff --git a/lib/tasks/doi.rake b/lib/tasks/doi.rake new file mode 100644 index 0000000000..2bc77d192c --- /dev/null +++ b/lib/tasks/doi.rake @@ -0,0 +1,14 @@ +# frozen_string_literal: true + +namespace :doi do + desc 'Add or update the Doi IdentifierScheme' + task add_identifier_scheme: :environment do + scheme = IdentifierScheme.find_or_create_by!(name: 'doi') do |s| + s.description = 'DOI service' + s.active = true + s.identifier_prefix = 'https://doi.org/' + end + + puts "DOI IdentifierScheme verified (ID: #{scheme.id})" + end +end \ No newline at end of file From cef18aea925597efb152bd73d3a8af2ed3f9959a Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:46:23 -0600 Subject: [PATCH 02/22] Add DOI prefill lookup and atomic identifier persistence to `ResearchOutputsController` - Updates `#new` and `#edit` to populate `@prefill_doi` (falling back to the existing DOI identifier on edit) and resolve metadata via `prefill_from_doi` when `params[:prefill_doi]` is supplied. - Adds `assign_doi_identifier` and `set_doi_identifier` to normalize, build/update, or mark cleared DOI identifiers for destruction prior to saving. - Wraps `#update` association clearing, DOI assignment, and `@research_output.update` in a `ResearchOutput.transaction` with `ActiveRecord::Rollback` so existing repositories and metadata standards are preserved if validation fails. - Re-renders `new` and `edit` in place with `flash.now[:alert]` and preserved `@prefill_doi` on validation errors. - Adds `prefill_from_doi` and `doi_error_message` private helpers to map DOI resolution statuses to localized user alerts. --- .../research_outputs_controller.rb | 81 ++++++++++++++++--- 1 file changed, 71 insertions(+), 10 deletions(-) diff --git a/app/controllers/research_outputs_controller.rb b/app/controllers/research_outputs_controller.rb index c05927b20c..a4ab0b7fc6 100644 --- a/app/controllers/research_outputs_controller.rb +++ b/app/controllers/research_outputs_controller.rb @@ -19,27 +19,39 @@ def index # GET /plans/:plan_id/research_outputs/new def new - @research_output = ResearchOutput.new(plan_id: @plan.id, output_type: '') + @research_output = ResearchOutput.new(plan_id: @plan.id, output_type: nil) authorize @research_output + + # Pre-fill from a DOI supplied in the query string + return unless params[:prefill_doi].present? + + @prefill_doi = params[:prefill_doi].presence + + prefill_from_doi(params[:prefill_doi]) end # GET /plans/:plan_id/research_outputs/:id/edit def edit authorize @research_output + @prefill_doi = params[:prefill_doi].presence || + @research_output.identifier_for_scheme(scheme: 'doi')&.value_without_scheme_prefix + prefill_from_doi(params[:prefill_doi]) if params[:prefill_doi].present? end # POST /plans/:plan_id/research_outputs - def create + def create # rubocop:disable Metrics/AbcSize args = process_byte_size.merge({ plan_id: @plan.id }) args = process_nillable_values(args: args) @research_output = ResearchOutput.new(args) authorize @research_output + assign_doi_identifier if @research_output.save redirect_to plan_research_outputs_path(@plan), notice: success_message(@research_output, _('added')) else - flash[:alert] = failure_message(@research_output, _('add')) + @prefill_doi = params[:prefill_doi].presence + flash.now[:alert] = failure_message(@research_output, _('add')) render 'research_outputs/new' end end @@ -51,20 +63,26 @@ def update args = process_nillable_values(args: args) authorize @research_output - # Clear any existing repository and metadata_standard selections. - @research_output.repositories.clear - @research_output.metadata_standards.clear + saved = ResearchOutput.transaction(requires_new: true) do + @research_output.repositories.clear + @research_output.metadata_standards.clear + assign_doi_identifier + raise ActiveRecord::Rollback unless @research_output.update(args) - if @research_output.update(args) + true + end + + if saved redirect_to plan_research_outputs_path(@plan), notice: success_message(@research_output, _('saved')) else - redirect_to edit_plan_research_output_path(@plan, @research_output), - alert: failure_message(@research_output, _('save')) + @prefill_doi = params[:prefill_doi].presence + flash.now[:alert] = failure_message(@research_output, _('save')) + render 'research_outputs/edit' end end - # rubocop:enable Metrics/AbcSize + # rubocop:enable Metrics/AbcSize # DELETE /plans/:plan_id/research_outputs/:id def destroy authorize @research_output @@ -144,6 +162,49 @@ def metadata_standard_search private + def prefill_from_doi(doi) + result = ExternalApis::DoiResolutionService.fetch_metadata(doi: doi) + if result[:status] == :ok + @research_output.assign_attributes( + result[:metadata].slice(:title, :description, :output_type, :release_date) + ) + else + flash.now[:alert] = doi_error_message(result[:status]) + end + end + + def doi_error_message(status) + case status + when :blank + _('DOI is required.') + when :invalid + _('Does not appear to be a valid DOI.') + when :not_found + _('Could not find metadata for the provided DOI. Please check the DOI and try again, or enter details manually.') + when :service_unavailable + _('DOI lookup service is currently unavailable. Please enter details manually.') + else + _('An unexpected error occurred.') + end + end + + def assign_doi_identifier + scheme = IdentifierScheme.by_name('doi').first + raw_doi = @prefill_doi || params[:prefill_doi] + return if scheme.blank? || raw_doi.nil? + + identifier = @research_output.identifier_for_scheme(scheme: scheme) + return identifier&.mark_for_destruction if raw_doi.blank? + + set_doi_identifier(scheme, identifier, raw_doi) + end + + def set_doi_identifier(scheme, identifier, raw_doi) + clean_doi = ExternalApis::DoiResolutionService.normalize_doi(raw_doi) || raw_doi.to_s.strip + target = identifier || @research_output.identifiers.build(identifier_scheme: scheme) + target.value = clean_doi + end + def output_params params.require(:research_output) .permit(%i[title abbreviation description output_type output_type_description From e00f49ba621e71dee02ffcb9c0671d0c86f76c9a Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:46:43 -0600 Subject: [PATCH 03/22] Create research_outputs_controller_spec.rb --- .../research_outputs_controller_spec.rb | 415 ++++++++++++++++++ 1 file changed, 415 insertions(+) create mode 100644 spec/requests/research_outputs_controller_spec.rb diff --git a/spec/requests/research_outputs_controller_spec.rb b/spec/requests/research_outputs_controller_spec.rb new file mode 100644 index 0000000000..96b4121db2 --- /dev/null +++ b/spec/requests/research_outputs_controller_spec.rb @@ -0,0 +1,415 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe 'ResearchOutputs DOI Fetching', type: :request do + let(:user) { create(:user) } + let(:plan) { create(:plan) } + let!(:doi_scheme) do + create(:identifier_scheme, name: 'doi', identifier_prefix: 'https://doi.org', active: true) + end + let(:doi) { '10.5281/zenodo.4884775' } + let(:datacite_base_url) { 'https://api.datacite.org' } + let(:crossref_base_url) { 'https://api.crossref.org' } + + let(:datacite_json) do + { + data: { + attributes: { + titles: [{ title: 'Example dataset' }], + descriptions: [ + { description: 'Abstract description text...', descriptionType: 'Abstract' } + ], + types: { resourceTypeGeneral: 'Dataset' }, + dates: [{ date: '2021-05-12', dateType: 'Issued' }] + } + } + }.to_json + end + + around do |example| + original_datacite_active = Rails.configuration.x.datacite.active + original_crossref_active = Rails.configuration.x.crossref.active + example.run + ensure + Rails.configuration.x.datacite.active = original_datacite_active + Rails.configuration.x.crossref.active = original_crossref_active + end + + before do + create(:role, :creator, user: user, plan: plan) + + sign_in user + + Rails.configuration.x.datacite.active = true + Rails.configuration.x.crossref.active = true + + Rails.cache.clear + end + + describe 'GET /plans/:plan_id/research_outputs/new with DOI prefill' do + it 'resolves the DOI once and pre-fills the form' do + datacite_request = stub_datacite_request( + body: datacite_json, + headers: { 'Content-Type' => 'application/json' } + ) + + get new_plan_research_output_path(plan, prefill_doi: doi) + + expect(response).to have_http_status(:ok) + expect(response.body).to include('Example dataset') + document = Nokogiri::HTML(response.body) + expect(document.at_css('#doi_lookup_input')['value']).to eq(doi) + expect(document.at_css('#research_output_output_type option[selected]')['value']).to eq('dataset') + expect(document.at_css('#research_output_release_date')['value']).to eq('2021-05-12') + expect(flash[:alert]).to be_nil + expect(datacite_request).to have_been_requested.once + end + + it 'supports metadata larger than the cookie session limit' do + large_description = "A long abstract #{'content ' * 800}" + large_datacite_json = JSON.parse(datacite_json) + large_datacite_json['data']['attributes']['descriptions'][0]['description'] = large_description + stub_datacite_request( + body: large_datacite_json.to_json, + headers: { 'Content-Type' => 'application/json' } + ) + + get new_plan_research_output_path(plan, prefill_doi: doi) + + expect(response).to have_http_status(:ok) + expect(response.body).to include('A long abstract') + expect(session[:doi_prefill_data]).to be_nil + end + + it 'rejects an invalid DOI without calling providers and stays on the form' do + invalid_doi = 'xxxx 10.1234/example' + datacite_request = stub_request(:get, /api\.datacite\.org/) + crossref_request = stub_request(:get, /api\.crossref\.org/) + + get new_plan_research_output_path(plan, prefill_doi: invalid_doi) + + expect(response).to have_http_status(:ok) + expect(datacite_request).not_to have_been_requested + expect(crossref_request).not_to have_been_requested + expect(response.body).to include('Does not appear to be a valid DOI.') + + document = Nokogiri::HTML(response.body) + expect(document.at_css('#doi_lookup_input')['value']).to eq(invalid_doi) + end + + context 'when resolving the DOI fails' do + it 'tells the user when providers are unavailable' do + stub_datacite_request(status: 500) + stub_crossref_request(status: 500) + + get new_plan_research_output_path(plan, prefill_doi: doi) + + expect(response).to have_http_status(:ok) + expect(response.body).to include('DOI lookup service is currently unavailable') + end + + it 'tells the user when metadata cannot be found and preserves context on new' do + missing_doi = '10.5281/not-found' + stub_datacite_request(target_doi: missing_doi, status: 404) + stub_crossref_request(target_doi: missing_doi, status: 404) + + get new_plan_research_output_path(plan, prefill_doi: missing_doi) + + expect(response).to have_http_status(:ok) + expect(response.body).to include('Could not find metadata for the provided DOI.') + + document = Nokogiri::HTML(response.body) + expect(document.at_css('#doi_lookup_input')['value']).to eq(missing_doi) + end + + it 'tells the user when metadata cannot be found and preserves context on edit' do + research_output = create(:research_output, plan: plan, title: 'Existing output') + missing_doi = '10.5281/not-found' + stub_datacite_request(target_doi: missing_doi, status: 404) + stub_crossref_request(target_doi: missing_doi, status: 404) + + get edit_plan_research_output_path(plan, research_output, prefill_doi: missing_doi) + + expect(response).to have_http_status(:ok) + expect(response.body).to include('Could not find metadata for the provided DOI.') + + document = Nokogiri::HTML(response.body) + expect(document.at_css('#research_output_title')['value']).to eq('Existing output') + expect(document.at_css('#doi_lookup_input')['value']).to eq(missing_doi) + end + end + end + + describe 'DOI persistence on research outputs' do + let(:research_output_params) do + { + title: 'Output with DOI', + output_type: 'dataset', + access: 'open', + prefill_doi: doi + } + end + + it 'persists the DOI identifier using the active doi IdentifierScheme when creating a research output' do + expect(IdentifierScheme.by_name('doi').first).to eq(doi_scheme) + + post plan_research_outputs_path(plan), params: { prefill_doi: doi, research_output: research_output_params } + + expect(response).to redirect_to(plan_research_outputs_path(plan)) + + research_output = ResearchOutput.order(:id).last + identifier = research_output.identifier_for_scheme(scheme: 'doi') + expect(identifier).to be_present + expect(identifier.identifier_scheme).to eq(doi_scheme) + expect(identifier.value_without_scheme_prefix).to eq(doi) + end + + it 'replaces the DOI identifier when updating a research output' do + research_output = create(:research_output, plan: plan, repositories_count: 0, metadata_standards_count: 0) + research_output.identifiers.create!(identifier_scheme: doi_scheme, value: '10.1111/original-doi') + + patch plan_research_output_path(plan, research_output), params: { + prefill_doi: doi, + research_output: { + title: research_output.title, + output_type: research_output.output_type, + access: research_output.access + } + } + + expect(response).to redirect_to(plan_research_outputs_path(plan)) + + research_output.reload + identifier = research_output.identifier_for_scheme(scheme: 'doi') + expect(research_output.identifiers.where(identifier_scheme: doi_scheme).count).to eq(1) + expect(identifier.value_without_scheme_prefix).to eq(doi) + end + + it 'shows the persisted DOI on the edit form when no prefill param is supplied' do + research_output = create(:research_output, plan: plan, repositories_count: 0, metadata_standards_count: 0) + research_output.identifiers.create!(identifier_scheme: doi_scheme, value: doi) + + get edit_plan_research_output_path(plan, research_output) + + expect(response).to have_http_status(:ok) + document = Nokogiri::HTML(response.body) + expect(document.at_css('#doi_lookup_input')['value']).to eq(doi) + end + + it 'updates the existing research output from DOI prefill without creating a new record' do + research_output = create( + :research_output, + plan: plan, + title: 'Original title', + description: 'Original description', + output_type: 'text', + release_date: '2020-01-01' + ) + + datacite_request = stub_datacite_request( + body: datacite_json, + headers: { 'Content-Type' => 'application/json' } + ) + + get edit_plan_research_output_path(plan, research_output, prefill_doi: doi) + + expect(response).to have_http_status(:ok) + document = Nokogiri::HTML(response.body) + expect(document.at_css('#research_output_title')['value']).to eq('Example dataset') + expect(document.at_css('#research_output_release_date')['value']).to eq('2021-05-12') + + original_count = ResearchOutput.count + + patch plan_research_output_path(plan, research_output), params: { + prefill_doi: doi, + research_output: { + title: 'Example dataset', + description: 'Abstract description text...', + output_type: 'dataset', + access: research_output.access, + release_date: '2021-05-12' + } + } + + expect(response).to redirect_to(plan_research_outputs_path(plan)) + expect(datacite_request).to have_been_requested.once + expect(ResearchOutput.count).to eq(original_count) + + research_output.reload + expect(research_output.title).to eq('Example dataset') + expect(research_output.description).to include('Abstract description text...') + expect(research_output.output_type).to eq('dataset') + expect(research_output.release_date.to_date).to eq(Date.parse('2021-05-12')) + expect(research_output.identifier_for_scheme(scheme: 'doi')&.value_without_scheme_prefix).to eq(doi) + end + + it 'removes the DOI identifier when clearing the DOI field on update' do + research_output = create(:research_output, plan: plan, repositories_count: 0, metadata_standards_count: 0) + research_output.identifiers.create!(identifier_scheme: doi_scheme, value: doi) + + patch plan_research_output_path(plan, research_output), params: { + prefill_doi: '', + research_output: { + title: research_output.title, + output_type: research_output.output_type, + access: research_output.access + } + } + + expect(response).to redirect_to(plan_research_outputs_path(plan)) + + research_output.reload + expect(research_output.identifier_for_scheme(scheme: 'doi')).to be_nil + end + + it 'does not create a research output when an invalid DOI is submitted on save' do + expect do + post plan_research_outputs_path(plan), + params: { prefill_doi: 'bad-doi', research_output: research_output_params } + end.not_to change(ResearchOutput, :count) + + expect(response).to have_http_status(:ok) + expect(response.body).to include('Does not appear to be a valid DOI.') + expect(Nokogiri::HTML(response.body).at_css('#doi_lookup_input')['value']).to eq('bad-doi') + end + + it 'does not update a research output when an invalid DOI is submitted on save' do + research_output = create(:research_output, plan: plan, title: 'Original title', repositories_count: 0, + metadata_standards_count: 0) + research_output.identifiers.create!(identifier_scheme: doi_scheme, value: doi) + + patch plan_research_output_path(plan, research_output), params: { + prefill_doi: 'bad-doi', + research_output: { title: 'Updated title', output_type: research_output.output_type, + access: research_output.access } + } + + expect(response).to have_http_status(:ok) + expect(response.body).to include('Does not appear to be a valid DOI.') + expect(Nokogiri::HTML(response.body).at_css('#doi_lookup_input')['value']).to eq('bad-doi') + expect(research_output.reload.title).to eq('Original title') + expect(research_output.identifier_for_scheme(scheme: 'doi')&.value_without_scheme_prefix).to eq(doi) + end + + describe 'replacing repository and metadata standard selections' do + let(:research_output) { create(:research_output, plan: plan, title: 'Original title') } + let(:new_repository) { create(:repository) } + let(:new_metadata_standard) { create(:metadata_standard) } + let(:updated_output_params) do + { + title: 'Updated title', + output_type: research_output.output_type, + access: research_output.access, + repositories_attributes: { '0' => { id: new_repository.id } }, + metadata_standards_attributes: { '0' => { id: new_metadata_standard.id } } + } + end + + before do + research_output.identifiers.create!(identifier_scheme: doi_scheme, value: doi) + end + + it 'preserves existing selections when an invalid DOI prevents an update' do + Rails.configuration.x.madmp.stubs(:enable_repository_selection).returns(true) + Rails.configuration.x.madmp.stubs(:enable_metadata_standard_selection).returns(true) + original_repository = research_output.repositories.first + original_metadata_standard = research_output.metadata_standards.first + + patch plan_research_output_path(plan, research_output), + params: { prefill_doi: 'bad-doi', research_output: updated_output_params } + + expect(response).to have_http_status(:ok) + expect(flash[:alert]).to match(/does not appear to be a valid DOI/i) + document = Nokogiri::HTML(response.body) + expect(document.at_css('#research_output_title')['value']).to eq('Updated title') + expect(document.at_css('#doi_lookup_input')['value']).to eq('bad-doi') + expect(document.at_css("input[name*='repositories_attributes'][value='#{new_repository.id}']")).to be_present + expect(document.at_css("input[name*='metadata_standards_attributes'][value='#{new_metadata_standard.id}']")) + .to be_present + + research_output.reload + aggregate_failures do + expect(research_output.title).to eq('Original title') + expect(research_output.identifier_for_scheme(scheme: 'doi')&.value_without_scheme_prefix).to eq(doi) + expect(research_output.repositories).to contain_exactly(original_repository) + expect(research_output.metadata_standards).to contain_exactly(original_metadata_standard) + end + end + + it 'replaces existing selections when the update succeeds' do + new_doi = '10.1111/new-doi' + + patch plan_research_output_path(plan, research_output), + params: { prefill_doi: new_doi, research_output: updated_output_params } + + expect(response).to redirect_to(plan_research_outputs_path(plan)) + research_output.reload + expect(research_output.title).to eq('Updated title') + expect(research_output.identifier_for_scheme(scheme: 'doi')&.value_without_scheme_prefix).to eq(new_doi) + expect(research_output.repositories).to contain_exactly(new_repository) + expect(research_output.metadata_standards).to contain_exactly(new_metadata_standard) + end + end + + it 'preserves existing selections when another validation prevents an update' do + research_output = create(:research_output, plan: plan) + original_repository = research_output.repositories.first + original_metadata_standard = research_output.metadata_standards.first + + patch plan_research_output_path(plan, research_output), params: { + prefill_doi: doi, + research_output: { title: '', output_type: research_output.output_type, access: research_output.access } + } + + expect(response).to have_http_status(:ok) + research_output.reload + expect(research_output.identifier_for_scheme(scheme: 'doi')).to be_nil + expect(research_output.repositories).to contain_exactly(original_repository) + expect(research_output.metadata_standards).to contain_exactly(original_metadata_standard) + end + + it 'removes existing selections when a valid update submits none' do + research_output = create(:research_output, plan: plan) + + patch plan_research_output_path(plan, research_output), params: { + prefill_doi: doi, + research_output: { title: research_output.title, output_type: research_output.output_type, + access: research_output.access } + } + + expect(response).to redirect_to(plan_research_outputs_path(plan)) + research_output.reload + expect(research_output.repositories).to be_empty + expect(research_output.metadata_standards).to be_empty + end + + it 'normalizes a full DOI URL when saved without clicking Fetch & Add' do + post plan_research_outputs_path(plan), params: { + prefill_doi: " https://doi.org/#{doi} ", + research_output: research_output_params + } + + identifier = ResearchOutput.order(:id).last.identifier_for_scheme(scheme: 'doi') + expect(identifier.value_without_scheme_prefix).to eq(doi) + end + end + + private + + def stub_datacite_request(target_doi: doi, status: 200, body: '', headers: {}) + escaped_path = CGI.escape(target_doi) + + stub_request(:get, "#{datacite_base_url}/dois/#{escaped_path}") + .with(headers: { 'Accept' => 'application/vnd.api+json' }) + .to_return(status: status, body: body, headers: headers) + end + + def stub_crossref_request(target_doi: doi, status: 200, body: '', headers: {}) + escaped_path = CGI.escape(target_doi) + + stub_request(:get, "#{crossref_base_url}/works/#{escaped_path}") + .with(headers: { 'Accept' => 'application/json' }) + .to_return(status: status, body: body, headers: headers) + end +end From e35033137c4aebedf95d0119c041f4d509a7da4b Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:47:02 -0600 Subject: [PATCH 04/22] Add doi format validation to `identifier.rb` --- app/models/identifier.rb | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/app/models/identifier.rb b/app/models/identifier.rb index 64b0082b7e..ae09dd2927 100644 --- a/app/models/identifier.rb +++ b/app/models/identifier.rb @@ -42,6 +42,8 @@ class Identifier < ApplicationRecord validate :value_uniqueness_without_scheme, unless: :schemed? + validate :valid_doi_format, if: -> { identifier_scheme&.name == 'doi' && value.present? } + # =============== # = Scopes = # =============== @@ -143,4 +145,11 @@ def value_uniqueness_with_scheme errors.add(:identifier_scheme, _('already assigned a value')) end end + + def valid_doi_format + raw_value = respond_to?(:value_without_scheme_prefix) ? value_without_scheme_prefix : value + return if ExternalApis::DoiResolutionService.normalize_doi(raw_value).present? + + errors.add(:value, _('does not appear to be a valid DOI')) + end end From dd4270b2c7c8265e0ba5e4dd884cdc7a6ba62f2a Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:47:26 -0600 Subject: [PATCH 05/22] Add development email to `dmproadmap.rb` initializer --- config/initializers/_dmproadmap.rb | 2 ++ 1 file changed, 2 insertions(+) diff --git a/config/initializers/_dmproadmap.rb b/config/initializers/_dmproadmap.rb index 200b7ddac5..e38e1634c2 100644 --- a/config/initializers/_dmproadmap.rb +++ b/config/initializers/_dmproadmap.rb @@ -35,6 +35,8 @@ class Application < Rails::Application config.x.organisation.do_not_reply_email 'do-not-reply@cc_curation_centre.org' # This email is used in email communications config.x.organisation.helpdesk_email = 'help@example.org' + # This email is used to contact developers + config.x.organisation.development_email = 'dmp-development@gw.alliancecan.ca' # Your organisation's telephone number - used on the contact us page config.x.organisation.telephone = '+1-123-123-1234' # Your organisation's address - used on the contact us page From 3bb135c1146c7931499152dc46d7550134773933 Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:50:44 -0600 Subject: [PATCH 06/22] Add crossref initializer --- config/initializers/external_apis/crossref.rb | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 config/initializers/external_apis/crossref.rb diff --git a/config/initializers/external_apis/crossref.rb b/config/initializers/external_apis/crossref.rb new file mode 100644 index 0000000000..f8f0d5111e --- /dev/null +++ b/config/initializers/external_apis/crossref.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +Rails.configuration.x.crossref.active = true +Rails.configuration.x.crossref.api_base_url = 'https://api.crossref.org' \ No newline at end of file From 89d48428c9a2f446f9947143131fd2948ad05419 Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:48:29 -0600 Subject: [PATCH 07/22] Add `ExternalApis::CrossrefService`for DOI metadata resolution - Implements `.api_base_url` and `.active?` configuration helpers. - Adds `.execute_api_get` to query the Crossref `/works/:doi` REST endpoint with polite `User-Agent` headers and 5-second open/read timeouts. - Adds `.parse_attributes` to extract title, sanitized abstract description, partial `issued.date-parts` release dates, mapped output type, and normalized DOI. - Adds `.map_crossref_type` to map Crossref work types to `ResearchOutput` enum values (`:dataset`, `:software`, `:text`, `:other`). - Adds `.log_and_notify_error` to log lookup failures and report them to Rollbar. --- .../external_apis/crossref_service.rb | 84 +++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 app/services/external_apis/crossref_service.rb diff --git a/app/services/external_apis/crossref_service.rb b/app/services/external_apis/crossref_service.rb new file mode 100644 index 0000000000..f40ac765b3 --- /dev/null +++ b/app/services/external_apis/crossref_service.rb @@ -0,0 +1,84 @@ +# frozen_string_literal: true + +require 'cgi' +module ExternalApis + # This service provides an interface to the CrossRef API + class CrossrefService < BaseService + class << self + def api_base_url + Rails.configuration.x.crossref&.api_base_url || super + end + + def active? + Rails.configuration.x.crossref&.active || false + end + + def execute_api_get(clean_doi) + url = "#{api_base_url}/works/#{CGI.escape(clean_doi)}" + headers = { + # Add User-Agent for polite API Access + # See https://www.crossref.org/documentation/retrieve-metadata/rest-api/access-and-authentication/ for more + 'User-Agent' => "DMPAssistant (mailto: #{Rails.configuration.x.organisation.development_email})", + 'Accept' => 'application/json' + } + HTTParty.get( + url, + headers: headers, + open_timeout: 5, + read_timeout: 5 + ) + end + + def parse_attributes(body, clean_doi) + json = JSON.parse(body).with_indifferent_access + work = json[:message] + return nil if work.blank? + + # The `issued.date-parts` array from Crossref can be partial ([YYYY], [YYYY, MM], or [YYYY, MM, DD]). + # We preserve the available precision only + date_parts = work.dig(:issued, :'date-parts', 0) || [] + release_date = date_parts.compact.join('-') if date_parts.any? + + { + title: work.dig(:title, 0), + # Crossref uses 'abstract' for its description field + description: ExternalApis::DoiResolutionService.sanitize_and_normalize_description(work[:abstract]), + output_type: map_crossref_type(work[:type]), + release_date: release_date, + doi: clean_doi + } + end + + # Maps all Crossref work-types safely to ResearchOutput enum system + # Run GET https://api.crossref.org/types to see all types + def map_crossref_type(type) + return :other if type.blank? + + case type.to_s.strip.downcase + when 'dataset', 'database' + :dataset + when 'component' + # Crossref uses 'component' to tag supplementary code snippets, software pieces, + # and independent data files attached to publications. + :software + when 'journal-article', 'proceedings-article', 'report', 'report-component', 'report-series', + 'book', 'book-chapter', 'book-section', 'book-part', 'book-series', 'book-set', + 'edited-book', 'monograph', 'reference-book', 'reference-entry', 'dissertation', + 'posted-content', 'peer-review', 'journal', 'journal-volume', 'journal-issue', + 'proceedings', 'proceedings-series' + :text + else + :other + end + end + + def log_and_notify_error(error, doi) + # Local logs for immediate debugging + Rails.logger.error "Crossref Service Error [fetch_metadata]: #{error.message}" + # External error tracking to notify the team via Rollbar + Rollbar.error(error, "Crossref Service Error [fetch_metadata] for DOI: #{doi}") + nil + end + end + end +end From fafbd1a23f56fab36d473d433c702ee2bffde062 Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:48:34 -0600 Subject: [PATCH 08/22] Create crossref_service_spec.rb --- .../external_apis/crossref_service_spec.rb | 95 +++++++++++++++++++ 1 file changed, 95 insertions(+) create mode 100644 spec/services/external_apis/crossref_service_spec.rb diff --git a/spec/services/external_apis/crossref_service_spec.rb b/spec/services/external_apis/crossref_service_spec.rb new file mode 100644 index 0000000000..e02e59752c --- /dev/null +++ b/spec/services/external_apis/crossref_service_spec.rb @@ -0,0 +1,95 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe ExternalApis::CrossrefService, type: :service do + let(:doi) { '10.5281/zenodo.4884775' } + + before do + Rails.configuration.x.crossref.active = true + end + + describe '.parse_attributes' do + context 'when given a valid JSON payload' do + let(:raw_json) do + { + message: { + title: ['Helper Function Test Title'], + abstract: 'Explicit abstract text.', + type: 'dataset', + issued: { 'date-parts': [[2023, 5, 12]] } + } + }.to_json + end + + it 'correctly extracts and structures all metadata fields' do + result = described_class.parse_attributes(raw_json, doi) + + expect(result).to eq({ + title: 'Helper Function Test Title', + description: 'Explicit abstract text.', + output_type: :dataset, + release_date: '2023-5-12', + doi: doi + }) + end + end + + context 'when the payload is missing message attributes entirely' do + it 'returns nil safely without raising an error' do + empty_json = { message: {} }.to_json + + expect(described_class.parse_attributes(empty_json, doi)).to be_nil + end + end + end + + describe 'description extraction helpers' do + context 'when the abstract field is empty or nil' do + let(:empty_desc_json) do + { + message: { + title: ['No Description Output'], + abstract: nil, + type: 'dataset' + } + }.to_json + end + + it 'returns nil for the description field' do + result = described_class.parse_attributes(empty_desc_json, doi) + + expect(result[:description]).to be_nil + end + end + end + + describe 'type mapping helpers' do + context 'when Crossref returns an unmapped or missing type' do + let(:unknown_type_json) do + { + message: { + title: ['Unknown Type Output'], + type: 'unrecognized-custom-type' + } + }.to_json + end + + it 'defaults the output type symbol to :other' do + result = described_class.parse_attributes(unknown_type_json, doi) + + expect(result[:output_type]).to eq(:other) + end + end + + context 'when mapping standard known Crossref general types' do + it 'correctly translates specific types into application symbols' do + dataset_json = { message: { title: ['T'], type: 'dataset' } }.to_json + article_json = { message: { title: ['T'], type: 'journal-article' } }.to_json + + expect(described_class.parse_attributes(dataset_json, doi)[:output_type]).to eq(:dataset) + expect(described_class.parse_attributes(article_json, doi)[:output_type]).to eq(:text) + end + end + end +end \ No newline at end of file From 811d40be8fe4fab1c4c7207615f3b7b28a81f197 Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:50:53 -0600 Subject: [PATCH 09/22] Add datacite initializer --- config/initializers/external_apis/datacite.rb | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 config/initializers/external_apis/datacite.rb diff --git a/config/initializers/external_apis/datacite.rb b/config/initializers/external_apis/datacite.rb new file mode 100644 index 0000000000..cf64de9bc9 --- /dev/null +++ b/config/initializers/external_apis/datacite.rb @@ -0,0 +1,4 @@ +# frozen_string_literal: true + +Rails.configuration.x.datacite.active = true +Rails.configuration.x.datacite.api_base_url = 'https://api.datacite.org' \ No newline at end of file From 948ac7da8a7041c9e663f58d40c38f58f1bbfa4b Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:50:24 -0600 Subject: [PATCH 10/22] Add `output_type_from_datacite` helper to `ResearchOutput` model --- app/models/research_output.rb | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/app/models/research_output.rb b/app/models/research_output.rb index 05e684172c..95bde60e8b 100644 --- a/app/models/research_output.rb +++ b/app/models/research_output.rb @@ -71,6 +71,19 @@ class ResearchOutput < ApplicationRecord # Ensure presence of the :output_type_description if the user selected 'other' validates_presence_of :output_type_description, if: -> { other? }, message: PRESENCE_MESSAGE + # ==================== + # = Class methods = + # ==================== + + # Helper method for extracting output type from datacite call in DataCite Service + def self.output_type_from_datacite(type) + return :other if type.blank? + return :model_representation if type == 'Model' # Handle explicit edge-case mapping + + normalized = type.underscore.to_sym + output_types.key?(normalized.to_s) ? normalized : :other + end + # ==================== # = Instance methods = # ==================== From 59097f586aff75a3d1e419e0737e2e5928b85d33 Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:50:30 -0600 Subject: [PATCH 11/22] Update research_output_spec.rb --- spec/models/research_output_spec.rb | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/spec/models/research_output_spec.rb b/spec/models/research_output_spec.rb index f09baf1d1e..57265848e6 100644 --- a/spec/models/research_output_spec.rb +++ b/spec/models/research_output_spec.rb @@ -65,4 +65,23 @@ true end end -end + + describe '.output_type_from_datacite' do + context 'when the type parameter is blank' do + it 'returns :other when type is nil' do + expect(described_class.output_type_from_datacite(nil)).to eq(:other) + end + + it 'returns :other when type is an empty string' do + expect(described_class.output_type_from_datacite('')).to eq(:other) + end + end + + context 'when the type parameter is not recognized by the system' do + it 'defaults safely back to :other' do + expect(described_class.output_type_from_datacite('UnrecognizedType')).to eq(:other) + expect(described_class.output_type_from_datacite('SomeFakeCategory')).to eq(:other) + end + end + end +end \ No newline at end of file From 3bf5b88c3fef46ea6b70ed2bec387050a196fcd5 Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:49:12 -0600 Subject: [PATCH 12/22] Add `ExternalApis::DataciteService` for DOI metadata resolution - Implements `.api_base_url` and `.active?` configuration helpers. - Adds `.execute_api_get` to query the DataCite `/dois/:doi` endpoint with JSON:API `Accept` headers and 5-second open/read timeouts. - Adds `.parse_attributes` to extract title, sanitized description (preferring `Abstract` with fallback to the first description), mapped `ResearchOutput` type, `Issued` release date, and normalized DOI. - Adds `.log_and_notify_error` to log lookup failures and report them to Rollbar. --- .../external_apis/datacite_service.rb | 71 +++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 app/services/external_apis/datacite_service.rb diff --git a/app/services/external_apis/datacite_service.rb b/app/services/external_apis/datacite_service.rb new file mode 100644 index 0000000000..d9aa58bc42 --- /dev/null +++ b/app/services/external_apis/datacite_service.rb @@ -0,0 +1,71 @@ +# frozen_string_literal: true + +require 'cgi' +module ExternalApis + # This service provides an interface to the DataCite API + class DataciteService < BaseService + class << self + def api_base_url + Rails.configuration.x.datacite&.api_base_url || super + end + + def active? + Rails.configuration.x.datacite&.active || false + end + + def extract_description(attrs) + descriptions = attrs[:descriptions] + return nil if descriptions.blank? + + abstract = descriptions.find { |d| d[:descriptionType] == 'Abstract' } + + # If an abstract hash was found, extract its text content. + # Otherwise, fall back to the very first text item in the array + target_description = abstract&.dig(:description) || descriptions.first&.dig(:description) + + ExternalApis::DoiResolutionService.sanitize_and_normalize_description(target_description) + end + + def execute_api_get(clean_doi) + url = "#{api_base_url}/dois/#{CGI.escape(clean_doi)}" + HTTParty.get( + url, + headers: { 'Accept' => 'application/vnd.api+json' }, + open_timeout: 5, + read_timeout: 5 + ) + end + + def parse_attributes(body, clean_doi) + json = JSON.parse(body).with_indifferent_access + attributes = json.dig(:data, :attributes) + return nil if attributes.blank? + + { + title: attributes.dig(:titles, 0, :title), + description: extract_description(attributes), + output_type: ResearchOutput.output_type_from_datacite(attributes.dig(:types, :resourceTypeGeneral)), + # Strictly use the 'Issued' date type. If unavailable, leave release_date nil + release_date: extract_issued_date(attributes), + doi: clean_doi + } + end + + def log_and_notify_error(error, doi) + # Local logs for immediate debugging + Rails.logger.error "DataCite Service Error [fetch_metadata]: #{error.message}" + # External error tracking to notify the team + Rollbar.error(error, "DataCite Service Error [fetch_metadata] for DOI: #{doi}") + nil + end + + private + + def extract_issued_date(attributes) + dates = attributes[:dates] || [] + issued_entry = dates.find { |d| d[:dateType]&.casecmp?('issued') } + issued_entry&.dig(:date) + end + end + end +end From de79d24b2a9889319f4bf54884a22d44f45b8019 Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:49:16 -0600 Subject: [PATCH 13/22] Create datacite_service_spec.rb --- .../external_apis/datacite_service_spec.rb | 175 ++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 spec/services/external_apis/datacite_service_spec.rb diff --git a/spec/services/external_apis/datacite_service_spec.rb b/spec/services/external_apis/datacite_service_spec.rb new file mode 100644 index 0000000000..1305cd2673 --- /dev/null +++ b/spec/services/external_apis/datacite_service_spec.rb @@ -0,0 +1,175 @@ +# frozen_string_literal: true + +require 'rails_helper' + +RSpec.describe ExternalApis::DataciteService, type: :service do + let(:doi) { '10.5281/zenodo.4884775' } + + before do + Rails.configuration.x.datacite.active = true + end + + describe '.parse_attributes' do + context 'when given a valid JSON payload' do + let(:raw_json) do + { + data: { + attributes: { + titles: [{ title: 'Helper Function Test Title' }], + descriptions: [ + { descriptionType: 'Other', description: 'Ignored description' }, + { descriptionType: 'Abstract', description: 'Explicit abstract text.' } + ], + types: { resourceTypeGeneral: 'Software' }, + dates: [ + { date: '2023-05-12', dateType: 'Issued' } + ] + } + } + }.to_json + end + + it 'correctly extracts and structures all metadata fields' do + result = described_class.parse_attributes(raw_json, doi) + + expect(result).to eq({ + title: 'Helper Function Test Title', + description: 'Explicit abstract text.', + output_type: :software, + release_date: '2023-05-12', + doi: doi + }) + end + end + + context 'when the payload is missing data attributes entirely' do + it 'returns nil safely without raising an error' do + empty_json = { data: {} }.to_json + + expect(described_class.parse_attributes(empty_json, doi)).to be_nil + end + end + end + + describe 'release_date extraction' do + context 'when an Issued date is present in the dates array' do + let(:issued_date_json) do + { + data: { + attributes: { + titles: [{ title: 'Issued Date Test' }], + dates: [ + { date: '2021-01-01', dateType: 'Created' }, + { date: '2022-03-15', dateType: 'Issued' } + ] + } + } + }.to_json + end + + it 'extracts the Issued date for release_date' do + result = described_class.parse_attributes(issued_date_json, doi) + + expect(result[:release_date]).to eq('2022-03-15') + end + end + + context 'when no Issued date is present in dates or dates array is missing' do + let(:no_issued_date_json) do + { + data: { + attributes: { + titles: [{ title: 'No Issued Date Test' }], + dates: [{ date: '2021-01-01', dateType: 'Created' }], + registered: '2023-05-12' + } + } + }.to_json + end + + it 'returns nil for release_date without falling back to another date' do + result = described_class.parse_attributes(no_issued_date_json, doi) + + expect(result[:release_date]).to be_nil + end + end + end + + describe 'description extraction helpers' do + context 'when descriptions do not contain an explicit Abstract type' do + let(:no_abstract_json) do + { + data: { + attributes: { + titles: [{ title: 'Fallback Desc Output' }], + descriptions: [ + { description: 'First general description block text.' }, + { description: 'Second description text.' } + ], + types: { resourceTypeGeneral: 'Text' } + } + } + }.to_json + end + + it 'falls back to picking the first available description element' do + result = described_class.parse_attributes(no_abstract_json, doi) + + expect(result[:description]).to eq('First general description block text.') + end + end + + context 'when the descriptions array is empty or nil' do + let(:empty_desc_json) do + { + data: { + attributes: { + titles: [{ title: 'No Description Output' }], + descriptions: [], + types: { resourceTypeGeneral: 'Dataset' } + } + } + }.to_json + end + + it 'returns nil for the description field' do + result = described_class.parse_attributes(empty_desc_json, doi) + + expect(result[:description]).to be_nil + end + end + end + + describe 'Resource Output type mapping' do + context 'when DataCite returns an unmapped or missing resourceTypeGeneral' do + let(:unknown_type_json) do + { + data: { + attributes: { + titles: [{ title: 'Unknown Type Output' }], + types: { resourceTypeGeneral: 'UnrecognizedType' } + } + } + }.to_json + end + + it 'defaults the output type symbol to :other' do + result = described_class.parse_attributes(unknown_type_json, doi) + + expect(result[:output_type]).to eq(:other) + end + end + + context 'when mapping standard known DataCite general types' do + it 'correctly translates specific types into application symbols' do + dataset_json = { data: { attributes: { titles: [{ title: 'T' }], + types: { resourceTypeGeneral: 'Dataset' } } } }.to_json + text_json = { data: { attributes: { titles: [{ title: 'T' }], + types: { resourceTypeGeneral: 'Text' } } } }.to_json + + expect(described_class.parse_attributes(dataset_json, doi)[:output_type]).to eq(:dataset) + expect(described_class.parse_attributes(text_json, doi)[:output_type]).to eq(:text) + end + end + end +end \ No newline at end of file From 1658d7102e895661e00ca935876fa89def1f643d Mon Sep 17 00:00:00 2001 From: momo3404 <85097704+momo3404@users.noreply.github.com> Date: Tue, 1 Dec 2026 13:49:55 -0600 Subject: [PATCH 14/22] Add `ExternalApis::DoiResolutionService` to orchestrate DOI lookup and normalization - Defines shared `MODERN_DOI_PATTERN` and `OLD_DOI_PATTERN` regex constants alongside `.normalize_doi` to strip `doi.org` and `dx.doi.org` prefixes and validate DOI syntax. - Implements `.fetch_metadata` with 5-minute top-level and per-provider `Rails.cache` caching, querying DataCite first and falling back to Crossref (`resolve_from_providers`, `execute_fetch`, `evaluate_statuses`). - Adds `.sanitize_and_normalize_description` to convert JATS XML markup (``, ``, ``, ``, ``) into standard HTML, strip ` + Bad Link + + HTML + + result = described_class.sanitize_and_normalize_description(malicious_input) + + expect(result).not_to include('