Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
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
103 changes: 99 additions & 4 deletions assets/js/components/deposit/overrides/PublishModal.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,108 @@
// CDS RDM is free software; you can redistribute it and/or modify it
// under the terms of the GPL-2.0 License; see LICENSE file for more details.

import React from "react";
import React, { useEffect, useState } from "react";
import PropTypes from "prop-types";
import { i18next } from "@translations/invenio_rdm_records/i18next";
import { SubmitReviewModal, PublishModal } from "@js/invenio_rdm_records";
import { parametrize } from "react-overridable";
import { useFormikContext } from "formik";
import { useSelector } from "react-redux";
import { http } from "react-invenio-forms";
import _get from "lodash/get";
import { Message, Icon } from "semantic-ui-react";

/**
* Informs the user about the CERN Research Community side effects of publishing.
* The decision (include / remove / nothing) is made by the backend
* (`get_community_inclusion_action`), so the rules live in a single place.
*
* Wraps the base modal so that the *deposit form* values (outer formik context)
* can be read; the modal renders its own inner formik context.
*/
const withCommunityInclusionMessages = (Modal) => {
// Render the original (non-overridable) modal: the registry maps the modal's
// container id to this very component, so using the overridable one recurses.
// `parametrize` is not used because its params win over props, which would
// discard the conditional `extraCheckboxes` below.
const ModalComponent = Modal.originalComponent || Modal;

const Wrapped = (props) => {
const { values } = useFormikContext();
const pid = useSelector((state) => state.deposit.record?.id);
const [action, setAction] = useState(null);

const access = _get(values, "access.record");
const resourceType = _get(values, "metadata.resource_type.id");

useEffect(() => {
let active = true;
http
.post("/api/cds/community-inclusion", {
pid,
access,
resource_type: resourceType,
})
.then((response) => active && setAction(response.data?.action))
.catch(() => active && setAction(null));
return () => {
active = false;
};
}, [pid, access, resourceType]);

let beforeContent = props.beforeContent;

Check warning on line 55 in assets/js/components/deposit/overrides/PublishModal.js

View workflow job for this annotation

GitHub Actions / JS

Must use destructuring props assignment
if (action === "remove") {
beforeContent = () => (
<Message visible negative className="rel-mb-1">
<p>
<Icon name="warning sign" />
{i18next.t(
"You are making this record restricted. The record, including all its versions, will be removed from the CERN Research Community (or its pending inclusion request will be cancelled). Do you want to continue?"
)}
</p>
</Message>
);
}

const includesInCommunity = action === "include";
return (
<ModalComponent
// The modals read `extraCheckboxes` once on mount, hence the `key`: it
// remounts the modal when the (async) decision arrives.
key={includesInCommunity ? "include" : "default"}
{...props}
{...parameters}
beforeContent={beforeContent}
extraCheckboxes={
includesInCommunity
? [...parameters.extraCheckboxes, communityInclusionCheckbox]
: parameters.extraCheckboxes
}
/>
);
};
Wrapped.propTypes = {
beforeContent: PropTypes.func,
};

Wrapped.defaultProps = {
beforeContent: undefined,
};

return Wrapped;
};

const communityInclusionCheckbox = {
id: "accept-community-inclusion-checkbox",
fieldPath: "acceptCommunityInclusion",
text: i18next.t(
"I understand that once published, this record will also be submitted for inclusion in the CERN Research Community."
),
};

export const parameters = {
extraCheckboxes: [
{
id: "accept-terms-of-service-checkbox",
fieldPath: "acceptTermsOfService",
text: (
<>
Expand Down Expand Up @@ -46,6 +140,7 @@
],
};

export const SubmitReviewModalComponent = parametrize(SubmitReviewModal, parameters);
export const SubmitReviewModalComponent =
withCommunityInclusionMessages(SubmitReviewModal);

export const PublishModalComponent = parametrize(PublishModal, parameters);
export const PublishModalComponent = withCommunityInclusionMessages(PublishModal);
4 changes: 2 additions & 2 deletions invenio.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ from invenio_app_rdm.config import \
from invenio_app_rdm.config import \
VOCABULARIES_DATASTREAM_WRITERS as DEFAULT_VOCABULARIES_DATASTREAM_WRITERS
from cds_rdm.clc_sync.services.components import ClcSyncComponent
from cds_rdm.components import CDSResourcePublication, CommitteeApprovalComponent, MintAlternateIdentifierComponent, SubjectsValidationComponent # PublicationInclusionComponent temporarily disabled
from cds_rdm.components import CDSResourcePublication, CommitteeApprovalComponent, MintAlternateIdentifierComponent, SubjectsValidationComponent, PublicationInclusionComponent
from cds_rdm.pids import validate_optional_doi_transitions
from cds_rdm.views import archive_link_render, frontpage_view_function, inspire_link_render
from cds_rdm.reviews.policy import CDSRecordVersionReviewPolicy
Expand Down Expand Up @@ -810,7 +810,7 @@ RDM_RECORDS_SERVICE_COMPONENTS = [
CDSResourcePublication,
ClcSyncComponent,
MintAlternateIdentifierComponent,
# PublicationInclusionComponent, # temporarily disabled
PublicationInclusionComponent,
VCSComponent,
]

Expand Down
167 changes: 111 additions & 56 deletions site/cds_rdm/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,10 @@
from marshmallow import ValidationError

from .tasks import (
sync_alternate_identifiers, # submit_community_inclusion_request temporarily disabled
find_open_inclusion_request_ids,
remove_from_scientific_community,
submit_community_inclusion_request,
sync_alternate_identifiers,
)


Expand Down Expand Up @@ -377,58 +380,110 @@ def publish(self, identity, draft=None, record=None):
)


# PublicationInclusionComponent temporarily disabled
# class PublicationInclusionComponent(ServiceComponent):
# """Auto-submit a community inclusion request to the CERN Scientific Community.
#
# Triggers on publish for public records whose resource type is listed in
# `CDS_CERN_SCIENTIFIC_RESOURCE_TYPES`. The request is created asynchronously
# after the publish transaction commits.
# """
#
# def _is_eligible(self, draft, record):
# """Return True when the record should be auto-submitted for community inclusion."""
# if not is_record_public(draft):
# return False
#
# resource_type = draft["metadata"]["resource_type"]["id"]
# research_resource_types = current_app.config.get(
# "CDS_CERN_SCIENTIFIC_RESOURCE_TYPES", set()
# )
# if resource_type not in research_resource_types:
# return False
#
# # Skip if the record is in the Scientific Community or the Related Research Community already
# # IMPORTANT:
# # 1. For thesis, we have the component CDSResourcePublication to validate the community selection
# # 2. For other resource types, it is highly unlikely that the record is NOT eligible for inclusion
# # in the CERN Research Community, since these works typically belong to CERN
# # On the off chance if there is a rare case, it will be dealt via support on case by case basis
# communities_to_skip = [
# current_app.config["CDS_CERN_SCIENTIFIC_COMMUNITY_ID"],
# current_app.config["CDS_CERN_RELATED_RESEARCH_COMMUNITY_ID"],
# ]
# for community_id in communities_to_skip:
# if not community_id:
# current_app.logger.error(
# f"Scientific Community IDs are not configured; "
# "skipping auto community inclusion for record %s.",
# record.pid.pid_value,
# )
# return False
# if community_id in record.parent.communities.ids:
# return False
#
# return True
#
# def publish(self, identity, draft=None, record=None, **kwargs):
# """Schedule community inclusion request after the record is published."""
# if not self._is_eligible(draft, record):
# return
#
# self.uow.register(
# TaskOp(
# submit_community_inclusion_request,
# record_id=record.pid.pid_value,
# )
# )
COMMUNITY_INCLUSION_INCLUDE = "include"
COMMUNITY_INCLUSION_REMOVE = "remove"


def _get_record_community_ids(parent):
"""Return the communities of a record, including the ones it is about to join.

Besides the communities the record belongs to, this covers the selected
(default) community and the receiver of a pending review, since records
submitted to a community are published only when the review is accepted.
"""
if not parent:
return set()
community_ids = set(parent.communities.ids)
default = parent.get("communities", {}).get("default")
if default:
community_ids.add(default)
review_community = (
parent.review is not None
and parent.review.receiver.reference_dict.get("community")
)
if review_community:
community_ids.add(review_community)
return community_ids


def get_community_inclusion_action(is_public, resource_type, parent=None):
"""Decide what happens with the CERN Scientific Community on publish.

Single source of truth, used by `PublicationInclusionComponent` and by the
deposit form (through the API) to inform the user before publishing.

:param is_public: whether the record will be public.
:param resource_type: resource type id of the record.
:param parent: parent of the record (None if not created yet). Communities
and inclusion requests are shared by all the versions of a record, so
the outcome applies to every version.
:returns: ``COMMUNITY_INCLUSION_INCLUDE``, ``COMMUNITY_INCLUSION_REMOVE``
or ``None``.
"""
scientific_id = current_app.config.get("CDS_CERN_SCIENTIFIC_COMMUNITY_ID")
if not scientific_id:
current_app.logger.error(
"Scientific Community ID is not configured; "
"skipping auto community inclusion."
)
return None

community_ids = _get_record_community_ids(parent)
has_open_request = bool(
parent and find_open_inclusion_request_ids(scientific_id, parent)
)

if not is_public:
# Only public records can be part of (or be pending for) the community.
if scientific_id in community_ids or has_open_request:
return COMMUNITY_INCLUSION_REMOVE
return None

research_resource_types = current_app.config.get(
"CDS_CERN_SCIENTIFIC_RESOURCE_TYPES", set()
)
if resource_type not in research_resource_types or has_open_request:
return None

# Skip if the record is in the Scientific Community or the Related Research Community already
# IMPORTANT:
# 1. For thesis, we have the component CDSResourcePublication to validate the community selection
# 2. For other resource types, it is highly unlikely that the record is NOT eligible for inclusion
# in the CERN Research Community, since these works typically belong to CERN
# On the off chance if there is a rare case, it will be dealt via support on case by case basis
communities_to_skip = [
scientific_id,
# The related research community is optional (may not be configured).
current_app.config.get("CDS_CERN_RELATED_RESEARCH_COMMUNITY_ID"),
]
if any(c and c in community_ids for c in communities_to_skip):
return None

return COMMUNITY_INCLUSION_INCLUDE


class PublicationInclusionComponent(ServiceComponent):
"""Auto-submit a community inclusion request to the CERN Scientific Community.

On publish, public records whose resource type is listed in
`CDS_CERN_SCIENTIFIC_RESOURCE_TYPES` are submitted to the community, and
records made restricted are removed from it (see
`get_community_inclusion_action`). The work is done asynchronously after the
publish transaction commits.
"""

def publish(self, identity, draft=None, record=None, **kwargs):
"""Schedule community inclusion (or removal) after the record is published."""
action = get_community_inclusion_action(
is_record_public(draft),
draft["metadata"]["resource_type"]["id"],
record.parent,
)
if action == COMMUNITY_INCLUSION_INCLUDE:
task = submit_community_inclusion_request
elif action == COMMUNITY_INCLUSION_REMOVE:
task = remove_from_scientific_community
else:
return

self.uow.register(TaskOp(task, record_id=record.pid.pid_value))
40 changes: 40 additions & 0 deletions site/cds_rdm/requests/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,53 @@
from invenio_requests.proxies import current_requests_service
from invenio_requests.resolvers.registry import ResolverRegistry

from ..components import get_community_inclusion_action
from .committee_approval import CommitteeApprovalRequest


def create_committee_approval_bp(app):
"""Create committee approval API blueprint."""
bp = Blueprint("cds_committee_approval", __name__)

@bp.route("/cds/community-inclusion", methods=["POST"])
@login_required
def community_inclusion():
"""Tell what publishing does with the CERN Scientific Community.

Used by the deposit form (``pid`` + the possibly unsaved ``access`` and
``resource_type``) and by the community submission request page
(``request_id``), to inform the user before publishing.
Returns ``{"action": "include"|"remove"|null}``.
"""
body = request.get_json(force=True) or {}
pid_value = body.get("pid")

try:
if body.get("request_id"):
req = current_requests_service.read(g.identity, body["request_id"])
pid_value = req.data.get("topic", {}).get("record")
draft = (
current_rdm_records_service.read_draft(g.identity, pid_value)
if pid_value
else None
)
except (PIDDoesNotExistError, PermissionDeniedError):
return jsonify({"message": "Record not found."}), 404

access = body.get("access")
resource_type = body.get("resource_type")
if draft is not None and (access is None or resource_type is None):
# Not given by the client: use the saved draft.
access = access or draft.data["access"]["record"]
resource_type = resource_type or draft.data["metadata"]["resource_type"]["id"]

action = get_community_inclusion_action(
access == "public",
resource_type,
draft._record.parent if draft is not None else None,
)
return jsonify({"action": action})

@bp.route("/records/<pid_value>/committee-approval", methods=["POST"])
@login_required
def submit_committee_approval(pid_value):
Expand Down
Loading
Loading