diff --git a/app/assets/stylesheets/blocks/_buttons.scss b/app/assets/stylesheets/blocks/_buttons.scss
index 46fd31b66e..29623c6aac 100644
--- a/app/assets/stylesheets/blocks/_buttons.scss
+++ b/app/assets/stylesheets/blocks/_buttons.scss
@@ -62,3 +62,13 @@
background-color: tint-color($color-primary-background, 40%);
border: none;
}
+
+#btn_prefill_doi {
+ background-color: $color-black;
+ color: $color-primary-text;
+ border: 1px solid $color-border-default;
+ padding: 0 20px;
+ font-size: 16px;
+ height: 40px;
+ white-space: nowrap;
+}
diff --git a/app/assets/stylesheets/blocks/_cards.scss b/app/assets/stylesheets/blocks/_cards.scss
index edb25d6e1f..bcc1ab9474 100644
--- a/app/assets/stylesheets/blocks/_cards.scss
+++ b/app/assets/stylesheets/blocks/_cards.scss
@@ -53,3 +53,8 @@
.card-default > .card-footer + .card-collapse > .card-body {
border-bottom-color: #ddd;
}
+
+#doi_lookup_panel {
+ background-color: #f9f9f9;
+ max-width: 600px;
+}
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
diff --git a/app/javascript/src/researchOutputs/form.js b/app/javascript/src/researchOutputs/form.js
index c57035f3c6..23de980235 100644
--- a/app/javascript/src/researchOutputs/form.js
+++ b/app/javascript/src/researchOutputs/form.js
@@ -1,6 +1,8 @@
import getConstant from '../utils/constants';
import { isUndefined, isObject } from '../utils/isType';
-import { Tinymce } from '../utils/tinymce.js';
+import { Tinymce } from '../utils/tinymce';
+
+const STATUS_CLASSES = 'd-none text-muted text-danger text-success';
$(() => {
const form = $('.research_output_form');
@@ -9,6 +11,62 @@ $(() => {
Tinymce.init({ selector: '#research_output_description' });
}
+ // Browsers can preserve the disabled button when restoring this page from
+ // the back-forward cache, so reset it when the page is shown again.
+ window.addEventListener('pageshow', (event) => {
+ if (event.persisted) {
+ $('#btn_prefill_doi')
+ .prop('disabled', false)
+ .text(getConstant('DOI_BUTTON_TEXT_DEFAULT'));
+ }
+ });
+
+ // Toggle DOI form visibility
+ $('body').on('click', '#btn_toggle_doi_form', (e) => {
+ e.preventDefault();
+ const panel = $('#doi_lookup_panel');
+
+ panel.toggleClass('d-none');
+
+ if (!panel.hasClass('d-none')) {
+ $('#doi_lookup_input').focus();
+ }
+ });
+
+ // Resolve the DOI in the new form request to avoid a second provider lookup.
+ $('body').on('click', '#btn_prefill_doi', (e) => {
+ e.preventDefault();
+ const button = $(e.currentTarget);
+ const inputField = $('#doi_lookup_input');
+ const statusText = $('#doi_lookup_status');
+
+ const doi = inputField.val().trim();
+ const cleanDoi = doi.replace(/^https?:\/\/(?:dx\.)?doi\.org\//i, '');
+
+ const prefillPath = button.data('prefill-path');
+
+ // Helper for DRY-ing state updates
+ const setLookupStatus = (type, message) => {
+ statusText.removeClass(STATUS_CLASSES).addClass(type).text(message);
+ };
+
+ if (!doi) {
+ setLookupStatus('text-danger', getConstant('DOI_VALIDATION_EMPTY'));
+ return;
+ }
+
+ const modernDoiPattern = new RegExp(`^(?:${getConstant('DOI_MODERN_PATTERN')})$`, 'i');
+ const oldDoiPattern = new RegExp(`^(?:${getConstant('DOI_OLD_PATTERN')})$`, 'i');
+
+ if (!modernDoiPattern.test(cleanDoi) && !oldDoiPattern.test(cleanDoi)) {
+ setLookupStatus('text-danger', getConstant('DOI_VALIDATION_INVALID'));
+ return;
+ }
+
+ button.prop('disabled', true).text(getConstant('DOI_VALIDATION_VERIFYING'));
+ window.location.href = `${prefillPath}?prefill_doi=${encodeURIComponent(cleanDoi)}`;
+ });
+
// Expands/Collapses the search results 'More info'/'Less info' section
$('body').on('click', '.modal-search-result .more-info a.more-info-link', (e) => {
e.preventDefault();
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
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 =
# ====================
diff --git a/app/services/external_apis/crossref_service.rb b/app/services/external_apis/crossref_service.rb
new file mode 100644
index 0000000000..2be773c4e7
--- /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}") if defined?(Rollbar)
+ nil
+ end
+ end
+ end
+end
diff --git a/app/services/external_apis/datacite_service.rb b/app/services/external_apis/datacite_service.rb
new file mode 100644
index 0000000000..2ca884f279
--- /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}") if defined?(Rollbar)
+ 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
diff --git a/app/services/external_apis/doi_resolution_service.rb b/app/services/external_apis/doi_resolution_service.rb
new file mode 100644
index 0000000000..c13cdbdcfe
--- /dev/null
+++ b/app/services/external_apis/doi_resolution_service.rb
@@ -0,0 +1,146 @@
+# frozen_string_literal: true
+
+module ExternalApis
+ # This service calls DataCite and Crossref services accordingly when parsing DOIs
+ class DoiResolutionService
+ SERVICES = [
+ [ExternalApis::DataciteService, 'datacite'],
+ [ExternalApis::CrossrefService, 'crossref']
+ ].freeze
+
+ ALLOWED_TAGS = %w[p br strong em ul ol li blockquote a].freeze
+ ALLOWED_ATTRIBUTES = %w[href title].freeze
+
+ # Browser-compatible patterns shared with the client-side validation.
+ MODERN_DOI_PATTERN = '10\.\d{4,9}/[-._;()/:A-Z0-9]+'
+ OLD_DOI_PATTERN = '10\.1002/[^\s]+'
+
+ # Matches ~99% of modern Crossref DOIs
+ MODERN_DOI_REGEX = /\A#{MODERN_DOI_PATTERN}\z/i
+
+ # Catch-all for early DOIs with complex/opaque formatting
+ OLD_DOI_REGEX = /\A#{OLD_DOI_PATTERN}\z/i
+
+ class << self
+ def active?
+ Rails.configuration.x.datacite&.active || Rails.configuration.x.crossref&.active
+ end
+
+ # Sanitizes and normalizes provider description markup server-side
+ def sanitize_and_normalize_description(description)
+ return nil if description.blank?
+
+ normalized = normalize_jats(description)
+
+ # Parse fragment and remove script/style tags along with their inner contents
+ doc = Nokogiri::HTML::DocumentFragment.parse(normalized)
+ doc.css('script, style').remove
+
+ sanitized = ActionController::Base.helpers.sanitize(
+ doc.to_html,
+ tags: ALLOWED_TAGS,
+ attributes: ALLOWED_ATTRIBUTES
+ )
+
+ sanitized&.strip
+ end
+
+ # Main function for the "Add Research Output by DOI" feature
+ def fetch_metadata(doi:)
+ return { status: :blank } if doi.blank?
+
+ clean_doi = normalize_doi(doi)
+ return { status: :invalid } if clean_doi.blank?
+
+ # Check top-level metadata cache first to prevent duplicate resolutions
+ cache_key = "doi_resolution/metadata/#{clean_doi.downcase}"
+ cached_result = Rails.cache.read(cache_key)
+ return cached_result if cached_result.present?
+
+ resolve_from_providers(clean_doi, cache_key)
+ end
+
+ def normalize_doi(doi)
+ cleaned = doi.to_s.strip.sub(%r{\Ahttps?://(?:dx\.)?doi\.org/}i, '')
+ cleaned if cleaned.match?(MODERN_DOI_REGEX) || cleaned.match?(OLD_DOI_REGEX)
+ end
+
+ private
+
+ def resolve_from_providers(clean_doi, cache_key)
+ statuses = []
+
+ # Check datacite first, fall back to crossref
+ SERVICES.each do |service_module, service_name|
+ res = execute_fetch(service_module, service_name, clean_doi)
+ if res.is_a?(Hash)
+ result = { status: :ok, metadata: res }
+ Rails.cache.write(cache_key, result, expires_in: 5.minutes)
+ return result
+ end
+
+ statuses << res
+ end
+
+ evaluate_statuses(statuses)
+ end
+
+ def evaluate_statuses(statuses)
+ active_statuses = statuses.reject { |s| s == :inactive }
+
+ if active_statuses.present? && active_statuses.all?(:not_found)
+ { status: :not_found }
+ else
+ { status: :service_unavailable }
+ end
+ end
+
+ def execute_fetch(service_module, service_name, clean_doi)
+ return :inactive unless service_module.active?
+
+ cache_key = "#{service_name}/metadata/#{clean_doi}"
+
+ return Rails.cache.read(cache_key) if Rails.cache.exist?(cache_key)
+
+ result = fetch_and_parse(service_module, clean_doi)
+ Rails.cache.write(cache_key, result, expires_in: 5.minutes) if cacheable_result?(result)
+ result
+ rescue SocketError, HTTParty::Error, Timeout::Error, JSON::ParserError => e
+ service_module.log_and_notify_error(e, clean_doi)
+ :error
+ end
+
+ def fetch_and_parse(service_module, clean_doi)
+ response = service_module.execute_api_get(clean_doi)
+ case response&.code
+ when 200
+ service_module.parse_attributes(response.body, clean_doi) || :error
+ when 404
+ :not_found
+ else
+ :error
+ end
+ end
+
+ def cacheable_result?(result)
+ result.is_a?(Hash) || result == :not_found
+ end
+
+ def normalize_jats(text)
+ string = text.dup
+ # Replace JATS tags with equivalent standard HTML tags
+ string.gsub!(/]*)?>/, '')
+ string.gsub!('
', '
')
+ string.gsub!(/]*)?>/, '')
+ string.gsub!(' ', '')
+ string.gsub!(/]*)?>/, '')
+ string.gsub!(' ', '')
+ string.gsub!(/]*)?>/, '')
+ string.gsub!(' ', '')
+ string.gsub!(/]*)?>/, ' ', '')
+ string
+ end
+ end
+ end
+end
diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb
index 491e2d8039..7da8a80ae1 100644
--- a/app/views/layouts/application.html.erb
+++ b/app/views/layouts/application.html.erb
@@ -146,7 +146,14 @@
CURRENT_LOCALE: LocaleService.to_gettext(locale: @current_locale.to_s),
MORE_INFO: _("More info"),
- LESS_INFO: _("Less info")
+ LESS_INFO: _("Less info"),
+
+ DOI_VALIDATION_EMPTY: _('Please enter a DOI string.'),
+ DOI_VALIDATION_INVALID: _('Does not appear to be a valid DOI.'),
+ DOI_VALIDATION_VERIFYING: _('Verifying...'),
+ DOI_BUTTON_TEXT_DEFAULT: _('Fetch & Add'),
+ DOI_MODERN_PATTERN: ExternalApis::DoiResolutionService::MODERN_DOI_PATTERN,
+ DOI_OLD_PATTERN: ExternalApis::DoiResolutionService::OLD_DOI_PATTERN,
}.to_json
%>
diff --git a/app/views/research_outputs/_form.html.erb b/app/views/research_outputs/_form.html.erb
index 7b3a016e89..2bbf40c09a 100644
--- a/app/views/research_outputs/_form.html.erb
+++ b/app/views/research_outputs/_form.html.erb
@@ -9,6 +9,37 @@ repository_tooltip = _("Repositories preserve, manage, and provide access to man
%>
<%= form_with model: @research_output, url: path, method: method, local: true do |f| %>
+<% if ExternalApis::DoiResolutionService.active? %>
+
+
+
+
+ <%= _("Pre-fill with DOI") %>
+
+
+ <%= _("Enter a DOI (e.g., 10.5281/zenodo.4884775) to automatically import its metadata into a new form.") %>
+
+
+
+
+
+ <%= _("Fetch & Add") %>
+
+
+
+
+
+
+
+<% end %>
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
diff --git a/config/initializers/external_apis/crossref.rb b/config/initializers/external_apis/crossref.rb
new file mode 100644
index 0000000000..fffcca214e
--- /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'
diff --git a/config/initializers/external_apis/datacite.rb b/config/initializers/external_apis/datacite.rb
new file mode 100644
index 0000000000..9fcdc5e911
--- /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'
diff --git a/lib/tasks/doi.rake b/lib/tasks/doi.rake
new file mode 100644
index 0000000000..30d0953e75
--- /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
diff --git a/spec/models/research_output_spec.rb b/spec/models/research_output_spec.rb
index f09baf1d1e..95c0279b4c 100644
--- a/spec/models/research_output_spec.rb
+++ b/spec/models/research_output_spec.rb
@@ -65,4 +65,23 @@
true
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
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
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..3cf0aeba17
--- /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
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..fc436b4753
--- /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
diff --git a/spec/services/external_apis/doi_resolution_service_spec.rb b/spec/services/external_apis/doi_resolution_service_spec.rb
new file mode 100644
index 0000000000..454efabec1
--- /dev/null
+++ b/spec/services/external_apis/doi_resolution_service_spec.rb
@@ -0,0 +1,208 @@
+# frozen_string_literal: true
+
+require 'rails_helper'
+
+RSpec.describe ExternalApis::DoiResolutionService, type: :service do
+ let(:user) { create(:user) }
+ let(:plan) { create(:plan) }
+ let(:doi) { '10.5281/zenodo.4884775' }
+ let(:datacite_base_url) { Rails.configuration.x.datacite.api_base_url }
+ let(:crossref_base_url) { Rails.configuration.x.crossref.api_base_url }
+
+ let(:datacite_body) do
+ { data: { attributes: {
+ titles: [{ title: 'DataCite Document' }],
+ descriptions: [{ description: 'DataCite Abstract' }],
+ types: { resourceTypeGeneral: 'Dataset' },
+ dates: [
+ { date: '2021-05-12', dateType: 'Issued' }
+ ]
+ } } }.to_json
+ end
+
+ let(:crossref_body) do
+ { message: {
+ title: ['Crossref Publication'],
+ abstract: 'Crossref Abstract',
+ type: 'journal-article',
+ issued: { 'date-parts': [[2026, 7]] }
+ } }.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)
+
+ Rails.configuration.x.datacite.active = true
+ Rails.configuration.x.crossref.active = true
+
+ Rails.cache.clear
+ end
+
+ describe '.fetch_metadata' do
+ context 'when the DOI parameter is blank' do
+ it 'returns a status of :blank' do
+ expect(described_class.fetch_metadata(doi: ' ')).to eq({ status: :blank })
+ end
+ end
+
+ context 'when the DOI fails pattern regex matching rules' do
+ it 'returns a status of :invalid' do
+ expect(described_class.fetch_metadata(doi: 'invalid-doi-string')).to eq({ status: :invalid })
+ end
+ end
+
+ context 'when DataCite has the record' do
+ it 'successfully cleans the input string, gets DataCite data, and ignores Crossref' do
+ messy_doi = " https://doi.org/#{doi} "
+
+ dc_stub = stub_request(:get, "#{datacite_base_url}/dois/10.5281%2Fzenodo.4884775")
+ .to_return(status: 200, body: datacite_body)
+
+ cr_stub = stub_request(:get, %r{api.crossref.org/works/})
+
+ result = described_class.fetch_metadata(doi: messy_doi)
+
+ expect(result[:status]).to eq(:ok)
+ expect(result[:metadata][:title]).to eq('DataCite Document')
+ expect(result[:metadata][:doi]).to eq(doi)
+ expect(result[:metadata][:release_date]).to eq('2021-05-12')
+ expect(dc_stub).to have_been_requested
+ expect(cr_stub).not_to have_been_requested
+ end
+ end
+
+ context 'when DataCite fails but Crossref has the record' do
+ it 'automatically falls back to Crossref' do
+ dc_stub = stub_request(:get, "#{datacite_base_url}/dois/10.5281%2Fzenodo.4884775")
+ .to_return(status: 404, body: '')
+
+ cr_stub = stub_request(:get, "#{crossref_base_url}/works/10.5281%2Fzenodo.4884775")
+ .to_return(status: 200, body: crossref_body)
+
+ result = described_class.fetch_metadata(doi: doi)
+
+ expect(result[:status]).to eq(:ok)
+ expect(result[:metadata][:title]).to eq('Crossref Publication')
+ expect(dc_stub).to have_been_requested
+ expect(cr_stub).to have_been_requested
+ end
+ end
+
+ context 'when both services fail to locate the asset' do
+ it 'returns status :not_found safely' do
+ stub_request(:get, /api.datacite.org/).to_return(status: 404)
+ stub_request(:get, /api.crossref.org/).to_return(status: 404)
+
+ expect(described_class.fetch_metadata(doi: doi)).to eq({ status: :not_found })
+ end
+ end
+
+ context 'when a provider times out or encounters an error' do
+ it 'returns status :service_unavailable when one provider times out and the other returns 404' do
+ stub_request(:get, /api.datacite.org/).to_raise(Timeout::Error)
+ stub_request(:get, /api.crossref.org/).to_return(status: 404)
+
+ expect(described_class.fetch_metadata(doi: doi)).to eq({ status: :service_unavailable })
+ end
+
+ it 'returns status :service_unavailable when all providers are inactive' do
+ Rails.configuration.x.datacite.active = false
+ Rails.configuration.x.crossref.active = false
+
+ expect(described_class.fetch_metadata(doi: doi)).to eq({ status: :service_unavailable })
+ end
+ end
+ end
+
+ describe '.execute_fetch' do
+ context 'when a service is explicitly deactivated in the configuration' do
+ it 'short-circuits instantly and returns inactive status without making network calls' do
+ Rails.configuration.x.datacite.active = false
+
+ dc_stub = stub_request(:get, /api.datacite.org/)
+
+ result = described_class.send(:execute_fetch, ExternalApis::DataciteService, 'datacite', doi)
+
+ expect(result).to eq(:inactive)
+ expect(dc_stub).not_to have_been_requested
+ end
+ end
+
+ context 'when the network layer encounters an error' do
+ it 'gracefully intercepts HTTP timeouts and returns error status instead of crashing' do
+ stub_request(:get, "#{datacite_base_url}/dois/10.5281%2Fzenodo.4884775")
+ .to_raise(Timeout::Error)
+
+ result = described_class.send(:execute_fetch, ExternalApis::DataciteService, 'datacite', doi)
+
+ expect(result).to eq(:error)
+ end
+
+ it 'gracefully intercepts JSON response parsing exceptions' do
+ stub_request(:get, "#{datacite_base_url}/dois/10.5281%2Fzenodo.4884775")
+ .to_return(status: 200, body: 'Not Valid JSON { [')
+
+ result = described_class.send(:execute_fetch, ExternalApis::DataciteService, 'datacite', doi)
+
+ expect(result).to eq(:error)
+ end
+ end
+ end
+
+ describe '.sanitize_and_normalize_description' do
+ it 'preserves supported formatting tags and attributes' do
+ raw_html = 'This is bold and a link .
'
+ result = described_class.sanitize_and_normalize_description(raw_html)
+
+ expect(result).to eq('This is bold and a link .
')
+ end
+
+ it 'converts known JATS XML elements into supported HTML' do
+ jats_xml =
+ 'Abstract text with bold and emphasis . '
+ result = described_class.sanitize_and_normalize_description(jats_xml)
+
+ expect(result).to eq('Abstract text with bold and emphasis .
')
+ end
+
+ it 'removes unknown/unsupported elements while retaining their text' do
+ unsupported_markup = 'Header Paragraph inner text
'
+ result = described_class.sanitize_and_normalize_description(unsupported_markup)
+
+ expect(result).to eq('HeaderParagraph inner text
')
+ end
+
+ it 'strips scripts, event-handler attributes, and unsafe URLs' do
+ malicious_input = <<~HTML
+ Safe text
+
+ Bad Link
+
+ HTML
+
+ result = described_class.sanitize_and_normalize_description(malicious_input)
+
+ expect(result).not_to include('