Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
90f75cd
Create `doi.rake`
momo3404 Dec 1, 2026
cef18ae
Add DOI prefill lookup and atomic identifier persistence to `Research…
momo3404 Dec 1, 2026
e00f49b
Create research_outputs_controller_spec.rb
momo3404 Dec 1, 2026
e350331
Add doi format validation to `identifier.rb`
momo3404 Dec 1, 2026
dd4270b
Add development email to `dmproadmap.rb` initializer
momo3404 Dec 1, 2026
3bb135c
Add crossref initializer
momo3404 Dec 1, 2026
89d4842
Add `ExternalApis::CrossrefService`for DOI metadata resolution
momo3404 Dec 1, 2026
fafbd1a
Create crossref_service_spec.rb
momo3404 Dec 1, 2026
811d40b
Add datacite initializer
momo3404 Dec 1, 2026
948ac7d
Add `output_type_from_datacite` helper to `ResearchOutput` model
momo3404 Dec 1, 2026
59097f5
Update research_output_spec.rb
momo3404 Dec 1, 2026
3bf5b88
Add `ExternalApis::DataciteService` for DOI metadata resolution
momo3404 Dec 1, 2026
de79d24
Create datacite_service_spec.rb
momo3404 Dec 1, 2026
1658d71
Add `ExternalApis::DoiResolutionService` to orchestrate DOI lookup an…
momo3404 Dec 1, 2026
6069147
Create doi_resolution_service_spec.rb
momo3404 Dec 1, 2026
8a6bf4b
Add DOI prefill button and panel custom CSS
momo3404 Dec 1, 2026
8a88a1b
Update `research_outputs/index.html.erb`
momo3404 Dec 1, 2026
0ccd5d9
Add DOI prefill lookup panel to research output form
momo3404 Dec 1, 2026
3e7326e
Add client-side DOI validation and prefill navigation to research out…
momo3404 Dec 1, 2026
4af3f4c
Add status message constants to `layouts/application.html.erb`
momo3404 Dec 1, 2026
84c46d6
Make rubocop happy
momo3404 Dec 1, 2026
18a7b70
Add Rollbar definition guard
momo3404 Dec 1, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions app/assets/stylesheets/blocks/_buttons.scss
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
5 changes: 5 additions & 0 deletions app/assets/stylesheets/blocks/_cards.scss
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
81 changes: 71 additions & 10 deletions app/controllers/research_outputs_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down
60 changes: 59 additions & 1 deletion app/javascript/src/researchOutputs/form.js
Original file line number Diff line number Diff line change
@@ -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');
Expand All @@ -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();
Expand Down
9 changes: 9 additions & 0 deletions app/models/identifier.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
# ===============
Expand Down Expand Up @@ -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
13 changes: 13 additions & 0 deletions app/models/research_output.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
# ====================
Expand Down
84 changes: 84 additions & 0 deletions app/services/external_apis/crossref_service.rb
Original file line number Diff line number Diff line change
@@ -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
Loading
Loading